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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With