1

I read text from a file line by line and split the strings with strtok, after that I put them into a array of pointer and wanted to rewrite the outputline in the same file.

For the first line it does work, but for the other lines - there is always the first character missing in the output textfile. I guess there must be something wrong with the position of the file pointer, but I don't get it.

int main(void){
    long pos = 0;
    char *token=NULL;
    char *list_text[100];

    char array[100]={0};

    FILE *file;

    file = fopen("list.txt", "r+");

    pos = ftell(file);

//read file in line by line

    while(fgets(array,100,file) != NULL){
        int i = 0;
        int j = 0;


//split string

        token = strtok(array," ");

        while(token != NULL) {
            printf("Token: %s\n", token);
            list_text[i++] = token;
            token = strtok(NULL," ");
            j++;
            }

//rewrite in file       

                fseek(file, pos, SEEK_SET);
                for (int i= 0; i < j; i++){
                fprintf(file, "%s ", list_text[i]);
                }

                fflush(file);
                pos = ftell(file);

                for (int i = 0; i < j; i++){        //reset
                    list_text[i] = 0;
                }

    }

    fclose(file);

   return(EXIT_SUCCESS);
}
Lavi
  • 11
  • 2

0 Answers0