user2684719
user2684719

Reputation:

Avoid newline on last line of output

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.

Upvotes: 3

Views: 3932

Answers (6)

Sumedh
Sumedh

Reputation: 404

You dont know the length, but there must be a condition which when becomes false, program will stop putting string into file, so inside the loop, write if condition which is same as terminating condition for your loop. for eg, for your above prog, it should be :

for(i=0;i<10;i++)
{ 
    if((i+1)!<10)    //executed when i=9
    fprintf(pFile,"%s",mystring);
    else             //executed for i=0 to 8
    fprintf(pFile,"%s\n",mystring);
}

Upvotes: 0

JackCColeman
JackCColeman

Reputation: 3807

In the following code snippet, 10 can be changed to any value without having to modify any other tests or ifs.

    pFile = fopen ("myfile.txt", "wb");

    fprintf(pFile, "%s", mystring);
    for(i = 1 ; i <  10 ; i++)
    {
        fprintf(pFile, "\n");
        fprintf(pFile, "%s", mystring);
    }
    fclose (pFile);

Upvotes: 0

zweihander
zweihander

Reputation: 6295

Since you are using a linked list, you can check if the current item has a next item. If it has, print a newline and if it doesn't, don't print a newline since it is the last item.

Upvotes: 0

johnish
johnish

Reputation: 390

I think something like this would be good:

fprintf (pFile, "%s%s", (i > 0 ? "\n" : ""), mystring);

Upvotes: 4

user1118321
user1118321

Reputation: 26345

An easy way would be to break the printing of the string and the printing of the newline into separate statements, then conditionalize the printing of the newline. Something like this;

for (i = 0; i < 10; i++)
{
    fprintf(pFile, "%s", mystring);
    if (i < 9) // Or whatever condition you need - could be "atEndOfList()" or whatever.
        fprintf (pFile, "\n");
}

Upvotes: 1

Gabe
Gabe

Reputation: 86718

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.

Upvotes: 8

Related Questions