Why does adding a n character while appending make it possible to print out the last appended line?Why is “while (!feof(file))” always wrong?C vs C++ file handlingHow do I save a text file into an array?trying to read a fileSegfault scanf and fprintffprintf has last print statement printing to standard outWhen does fgets stop reading a line?C - How fgets works with mutiple callsWhy my “fprintf()” does not override the original “fprintf()”?Print last few lines of a text fileWhy does this code print lines and not single chars

How to politely tell someone they did not hit "reply to all" in an email?

How did NASA Langley end up with the first 737?

Can the product of any two aperiodic functions which are defined on the entire number line be periodic?

In general, would I need to season a meat when making a sauce?

Why would Ryanair allow me to book this journey through a third party, but not through their own website?

Where have Brexit voters gone?

Do photons bend spacetime or not?

Is it legal to have an abortion in another state or abroad?

Specific alignment within beginalign environment

Can a British citizen living in France vote in both France and Britain in the European Elections?

Is the field of q-series 'dead'?

What is the difference between singing and speaking?

Is Jon Snow the last of his House?

Python program to take in two strings and print the larger string

I know that there is a preselected candidate for a position to be filled at my department. What should I do?

Question in discrete mathematics about group permutations

Website returning plaintext password

Did 20% of US soldiers in Vietnam use heroin, 95% of whom quit afterwards?

Which European Languages are not Indo-European?

What does $!# mean in Shell scripting?

Is it truly impossible to tell what a CPU is doing?

How to let other coworkers know that I don't share my coworker's political views?

Count rotary dial pulses in a phone number (including letters)

Why aren't space telescopes put in GEO?



Why does adding a n character while appending make it possible to print out the last appended line?


Why is “while (!feof(file))” always wrong?C vs C++ file handlingHow do I save a text file into an array?trying to read a fileSegfault scanf and fprintffprintf has last print statement printing to standard outWhen does fgets stop reading a line?C - How fgets works with mutiple callsWhy my “fprintf()” does not override the original “fprintf()”?Print last few lines of a text fileWhy does this code print lines and not single chars






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am trying to write some C code that appends a line of text to a file, and then simply display it line by line. When I open the file in append mode and add a line using fprintf, the line gets added and I can see it when I open the file with a text editor. However when I call a function to display all lines (which works fine before the new text is appended), I get all the lines until the last but excluding the new appended line.



Here is the code I'm working with. The first function just adds a new line, and the second function just reads all the lines. The read_csv() works initially when I haven't appended any lines through code and have just used a text editor to add my initial lines.



void add_record(const char* csv_filename)

FILE *f = fopen(csv_filename,"at");
char str="My appended line "
fprintf(f,"%s",str);
fclose(f);


void read_csv(const char* csv_filename)

FILE *f = fopen(csv_filename,"rt");
char str[MAX];
fgets(str,MAX,f);
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fclose(f);




Now I found two fixes to my problem but I don't exactly understand why they work.



Fix 1 : Adding an extra fgets() prints the missing appending line when I'm trying to display it, however when I use it to display my original text file it prints the last line twice..so not a good fix.



fgets(str,MAX,f)
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fgets(str,MAX,f)


Fix 2 : Adding a new line character at the along with the string appended fixes the problem perfectly and everything is smooth. All the lines get displayed when I call read_csv().



char str="My appended line "
fprintf(f,"%sn",str)


Looking at the docs for fgets(), it says it reads until either a new line character or eof has reached(whichever occurs first), so I don't understand why my appended line get ignored by fgets().



When fgets() reaches the last line(which it skips) the situation I presume is something like this: it gets a string with " text text text eof",and it breaks out the loop skipping the print statement. But then when I use an extra fgets() outside the while loop it works. Also when I add a new line and the situation is a string like " text text text n eof", it doesn't quit the loop and goes on to display it.



I would really appreciate if I could get some info on what is happening and why these two fixes work. I suspect it is something to do with the feof detecting an eof or some specifics about fgets but I couldn't find anything satisfactory online.



Thank you so much in advance for taking the time to read and respond.










share|improve this question



















  • 2





    while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

    – Kamil Cuk
    Mar 24 at 2:46












  • Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

    – Rahul Kumar
    Mar 24 at 2:49











  • Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

    – Kamil Cuk
    Mar 24 at 2:50












  • Why is “while (!feof(file))” always wrong?

    – ShadowRanger
    Mar 24 at 2:53











  • I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

    – Rahul Kumar
    Mar 24 at 2:55

















1















I am trying to write some C code that appends a line of text to a file, and then simply display it line by line. When I open the file in append mode and add a line using fprintf, the line gets added and I can see it when I open the file with a text editor. However when I call a function to display all lines (which works fine before the new text is appended), I get all the lines until the last but excluding the new appended line.



Here is the code I'm working with. The first function just adds a new line, and the second function just reads all the lines. The read_csv() works initially when I haven't appended any lines through code and have just used a text editor to add my initial lines.



void add_record(const char* csv_filename)

FILE *f = fopen(csv_filename,"at");
char str="My appended line "
fprintf(f,"%s",str);
fclose(f);


void read_csv(const char* csv_filename)

FILE *f = fopen(csv_filename,"rt");
char str[MAX];
fgets(str,MAX,f);
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fclose(f);




Now I found two fixes to my problem but I don't exactly understand why they work.



Fix 1 : Adding an extra fgets() prints the missing appending line when I'm trying to display it, however when I use it to display my original text file it prints the last line twice..so not a good fix.



fgets(str,MAX,f)
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fgets(str,MAX,f)


Fix 2 : Adding a new line character at the along with the string appended fixes the problem perfectly and everything is smooth. All the lines get displayed when I call read_csv().



char str="My appended line "
fprintf(f,"%sn",str)


Looking at the docs for fgets(), it says it reads until either a new line character or eof has reached(whichever occurs first), so I don't understand why my appended line get ignored by fgets().



When fgets() reaches the last line(which it skips) the situation I presume is something like this: it gets a string with " text text text eof",and it breaks out the loop skipping the print statement. But then when I use an extra fgets() outside the while loop it works. Also when I add a new line and the situation is a string like " text text text n eof", it doesn't quit the loop and goes on to display it.



I would really appreciate if I could get some info on what is happening and why these two fixes work. I suspect it is something to do with the feof detecting an eof or some specifics about fgets but I couldn't find anything satisfactory online.



Thank you so much in advance for taking the time to read and respond.










share|improve this question



















  • 2





    while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

    – Kamil Cuk
    Mar 24 at 2:46












  • Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

    – Rahul Kumar
    Mar 24 at 2:49











  • Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

    – Kamil Cuk
    Mar 24 at 2:50












  • Why is “while (!feof(file))” always wrong?

    – ShadowRanger
    Mar 24 at 2:53











  • I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

    – Rahul Kumar
    Mar 24 at 2:55













1












1








1








I am trying to write some C code that appends a line of text to a file, and then simply display it line by line. When I open the file in append mode and add a line using fprintf, the line gets added and I can see it when I open the file with a text editor. However when I call a function to display all lines (which works fine before the new text is appended), I get all the lines until the last but excluding the new appended line.



Here is the code I'm working with. The first function just adds a new line, and the second function just reads all the lines. The read_csv() works initially when I haven't appended any lines through code and have just used a text editor to add my initial lines.



void add_record(const char* csv_filename)

FILE *f = fopen(csv_filename,"at");
char str="My appended line "
fprintf(f,"%s",str);
fclose(f);


void read_csv(const char* csv_filename)

FILE *f = fopen(csv_filename,"rt");
char str[MAX];
fgets(str,MAX,f);
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fclose(f);




Now I found two fixes to my problem but I don't exactly understand why they work.



Fix 1 : Adding an extra fgets() prints the missing appending line when I'm trying to display it, however when I use it to display my original text file it prints the last line twice..so not a good fix.



fgets(str,MAX,f)
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fgets(str,MAX,f)


Fix 2 : Adding a new line character at the along with the string appended fixes the problem perfectly and everything is smooth. All the lines get displayed when I call read_csv().



char str="My appended line "
fprintf(f,"%sn",str)


Looking at the docs for fgets(), it says it reads until either a new line character or eof has reached(whichever occurs first), so I don't understand why my appended line get ignored by fgets().



When fgets() reaches the last line(which it skips) the situation I presume is something like this: it gets a string with " text text text eof",and it breaks out the loop skipping the print statement. But then when I use an extra fgets() outside the while loop it works. Also when I add a new line and the situation is a string like " text text text n eof", it doesn't quit the loop and goes on to display it.



I would really appreciate if I could get some info on what is happening and why these two fixes work. I suspect it is something to do with the feof detecting an eof or some specifics about fgets but I couldn't find anything satisfactory online.



Thank you so much in advance for taking the time to read and respond.










share|improve this question
















I am trying to write some C code that appends a line of text to a file, and then simply display it line by line. When I open the file in append mode and add a line using fprintf, the line gets added and I can see it when I open the file with a text editor. However when I call a function to display all lines (which works fine before the new text is appended), I get all the lines until the last but excluding the new appended line.



Here is the code I'm working with. The first function just adds a new line, and the second function just reads all the lines. The read_csv() works initially when I haven't appended any lines through code and have just used a text editor to add my initial lines.



void add_record(const char* csv_filename)

FILE *f = fopen(csv_filename,"at");
char str="My appended line "
fprintf(f,"%s",str);
fclose(f);


void read_csv(const char* csv_filename)

FILE *f = fopen(csv_filename,"rt");
char str[MAX];
fgets(str,MAX,f);
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fclose(f);




Now I found two fixes to my problem but I don't exactly understand why they work.



Fix 1 : Adding an extra fgets() prints the missing appending line when I'm trying to display it, however when I use it to display my original text file it prints the last line twice..so not a good fix.



fgets(str,MAX,f)
while(!feof(f))
fputs(str,stdout);
fputs("n",stdout);
fgets(str,MAX,f);

fgets(str,MAX,f)


Fix 2 : Adding a new line character at the along with the string appended fixes the problem perfectly and everything is smooth. All the lines get displayed when I call read_csv().



char str="My appended line "
fprintf(f,"%sn",str)


Looking at the docs for fgets(), it says it reads until either a new line character or eof has reached(whichever occurs first), so I don't understand why my appended line get ignored by fgets().



When fgets() reaches the last line(which it skips) the situation I presume is something like this: it gets a string with " text text text eof",and it breaks out the loop skipping the print statement. But then when I use an extra fgets() outside the while loop it works. Also when I add a new line and the situation is a string like " text text text n eof", it doesn't quit the loop and goes on to display it.



I would really appreciate if I could get some info on what is happening and why these two fixes work. I suspect it is something to do with the feof detecting an eof or some specifics about fgets but I couldn't find anything satisfactory online.



Thank you so much in advance for taking the time to read and respond.







c file-io append fgets feof






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 2:50







Rahul Kumar

















asked Mar 24 at 2:41









Rahul KumarRahul Kumar

63




63







  • 2





    while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

    – Kamil Cuk
    Mar 24 at 2:46












  • Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

    – Rahul Kumar
    Mar 24 at 2:49











  • Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

    – Kamil Cuk
    Mar 24 at 2:50












  • Why is “while (!feof(file))” always wrong?

    – ShadowRanger
    Mar 24 at 2:53











  • I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

    – Rahul Kumar
    Mar 24 at 2:55












  • 2





    while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

    – Kamil Cuk
    Mar 24 at 2:46












  • Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

    – Rahul Kumar
    Mar 24 at 2:49











  • Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

    – Kamil Cuk
    Mar 24 at 2:50












  • Why is “while (!feof(file))” always wrong?

    – ShadowRanger
    Mar 24 at 2:53











  • I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

    – Rahul Kumar
    Mar 24 at 2:55







2




2





while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

– Kamil Cuk
Mar 24 at 2:46






while(!feof(f)) is always wrong, you are failing to read after the last line. Why don't you check the return value of fgets?

– Kamil Cuk
Mar 24 at 2:46














Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

– Rahul Kumar
Mar 24 at 2:49





Thanks for your reply. Could I ask why the while condition is always wrong? As it displays all lines perfectly if I call it before I have appended a line.

– Rahul Kumar
Mar 24 at 2:49













Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

– Kamil Cuk
Mar 24 at 2:50






Because then fgets does not set feof as it quits after reading newline. So the feof condition is not set, as the stream didn't read eof. Then the next fgets reads zero characters and set's feof.

– Kamil Cuk
Mar 24 at 2:50














Why is “while (!feof(file))” always wrong?

– ShadowRanger
Mar 24 at 2:53





Why is “while (!feof(file))” always wrong?

– ShadowRanger
Mar 24 at 2:53













I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

– Rahul Kumar
Mar 24 at 2:55





I tried checking the return value of fgets(), and it was NULL just after exiting the loop, which means it reached the end of file, correct?

– Rahul Kumar
Mar 24 at 2:55












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320286%2fwhy-does-adding-a-n-character-while-appending-make-it-possible-to-print-out-the%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid …


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320286%2fwhy-does-adding-a-n-character-while-appending-make-it-possible-to-print-out-the%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?