Begumm
Begumm

Reputation: 69

Writing line by line to file with c

I have a question about writing words to a file. It is wanted that a word coming from a file will be written to an intermediate file named as temp2-i. Here i changes according to the word length.

Here is my code:

 while(!feof(args->file))
{
    if(EOF!=fscanf(args->file,"%s",word))
    {
        //create intermediate file name as tempj-i
        sprintf(str, "%d", j);
        sprintf(str2 , "%d" , i);

        strcpy(result , "temp");
        strcat(result, str);
        strcat(result , "-");
        strcat(result, str2);

        //create intermediate file
        destFile = fopen(result , "w"); --> here is problem
        if (destFile== NULL) {
            printf("Error in opening a file..", destFile);
        }

        fprintf(destFile , "%s", word);
        fprintf(destFile ,"%s" , " ");

        fclose(destFile);
        count++;


    }
}

  fclose(args->file);
  pthread_exit(0);
}

My question is even if there are many words to be written to the same intermediate file , at the end only one of them is written. How can I solve this problem?

Upvotes: 0

Views: 697

Answers (2)

Devolus
Devolus

Reputation: 22104

You are opening the file for each individual word separately. If this is intentional (why?) you would have to use "wa" as the open mode. If this is not intentional you should open the file outside the loop, and close it when the loop exits.

destFile = fopen(result , "w"); --> here is problem

must be

destFile = fopen(result , "wa");

This will cause the writing to go to the end of the file before writing, appending your new data.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249652

It looks like you are opening the file each time through the loop. Presumably you want to open it just once, outside the loop, and write to it multiple times.

Upvotes: 1

Related Questions