Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid newline on last line of output

Tags:

c

I want to write some data into a file line by line.

   int main ()
   {
        char* mystring = "joe";
        int i  ;
        FILE * pFile;
        pFile = fopen ("myfile.txt", "wb");
        for(i = 0 ; i <  10 ; i++)
        {
            fprintf(pFile,"%s\n",mystring);
        }
        fclose (pFile);
        return 0;
  }

I am using new line especial charater so that new data will go into next line.

Problem is at last line i dont want newline.

Note: Just for the demo i use for loop. In real situation I used linked list to iterate the data hence I don't the length.

Please tell me how to remove last line from file.


1 Answers

There are a couple simple answers:

A. Truncate the file by one newline character when you get to the end of your list.

B. Print the newline before the string, but only if not the first line:

if (i > 0)
    fputs("\n", pFile);
fputs(mystring, pFile);

Note that this doesn't rely on having a for loop; it just requires that i only be 0 for the first line.

like image 149
Gabe Avatar answered Dec 08 '25 17:12

Gabe