Append to File

J

Jonathan Shan

Hello everybody,

For some strange reason my output to file keeps writing to the top
instead of bottom.

Here is the code that exhibits the problem:

void printfile(int i)
{
FILE* write;
write = fopen("write.txt", "a+");
fprintf(write, "%i \n", i);
}
int main()
{

int i;
for (i = 0; i < 10 ; i++)
{
printfile(i);
}
return 0;
}

The output is:
9
8
7
....
instead of the "expected"
0
1
2
....

I already realize one solution is to reverse the for loop..

Jonathan Shan
 
T

Tak-Shing Chan

Hello everybody,

For some strange reason my output to file keeps writing to the top
instead of bottom.

Here is the code that exhibits the problem:

void printfile(int i)
{
FILE* write;
write = fopen("write.txt", "a+");
fprintf(write, "%i \n", i);
}
int main()
{

int i;
for (i = 0; i < 10 ; i++)
{
printfile(i);
}
return 0;
}

The output is:
9
8
7
...
instead of the "expected"
0
1
2
...

I already realize one solution is to reverse the for loop..

Jonathan Shan

You should close the file before reopening it.

Tak-Shing
 
K

Kenneth Brody

Jonathan said:
Hello everybody,

For some strange reason my output to file keeps writing to the top
instead of bottom.

Here is the code that exhibits the problem:

void printfile(int i)
{
FILE* write;
write = fopen("write.txt", "a+");
fprintf(write, "%i \n", i);
}

You create a new FILE* each time you call printfile(), and you
never close them.
int main()
{

int i;
for (i = 0; i < 10 ; i++)
{
printfile(i);
}
return 0;
}

The output is:
9
8
7
...
instead of the "expected"
0
1
2
...

I already realize one solution is to reverse the for loop..

What you have done is open the "write.txt" file 10 times, and
written the numbers to each separately buffered stream. When
main() returns, the C runtime library closes the files that you
have left open, in some order known only to the compiler writers.
From the behavior, it appears that it closes them in the reverse
order you opened them, causing that stream's output to be appended
to the file.

The solution is to either fclose() the file in printfile(), or
only open the file once.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:[email protected]>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top