Reputation: 467
I have a simple program (which uses threads) called ./mpace
that uses printf()
in the thread function. When I ran it from the terminal, the output is printed as it should, but when I type:
**./mpace > text**
the file created is empty. The funny thing is that yesterday it worked perfectly. I typed:
echo "test" > text
to check if there is a serious problem with this function, but it worked. So, what could be the reason my program unexpectedly started failing to write to file?
Please note I'd prefer not to use fprintf()
from my code, since time consumption is essential.
Thanks a lot, the problem was solved simply by using fflush(stdout). I thought printing in a new line would flush the channel, but as paxdiablo explains in a comment here it doesn't:
Why does printf not flush after the call unless a newline is in the format string?
You are right that one should offer as much as information as he can,but I thought that sharing 100 lines of code for a single printf() would be a drag for you to read. I see this was a bad decision, since not using fflush and the fact that the program is being terminated by a signal both contributed to the problem and should have been made known.
Upvotes: 0
Views: 140
Reputation: 5297
Well it could be because you are using > instead of >> and probably somehow your code (which by the way, you didn't share it) contains a newline (blank) and delete the old one. let me show you an Example.
Let say we have the following file called file1.txt which contains the following information:
Michael Jimmy Dolores
And I wont to extract the name Jimmy and redirect the output to another file called file2.txt
cat file1.txt | grep "Jimmy" > file2.txt
Now the file2.txt contains:
Jimmy
Now lets run this command 3-4 times and check that file again:
cat file2.txt
Output:
Jimmy
Why is this ? it should be:
Jimmy Jimmy Jimmy Jimmy
Well becouse i used > instead of >>. Now let's try again:
michi@michi-laptop:~$ cat file1.txt | grep "Jimmy" >> file2.txt
michi@michi-laptop:~$ cat file1.txt | grep "Jimmy" >> file2.txt
michi@michi-laptop:~$ cat file1.txt | grep "Jimmy" >> file2.txt
michi@michi-laptop:~$ cat file1.txt | grep "Jimmy" >> file2.txt
Output:
Jimmy Jimmy Jimmy Jimmy Jimmy
This could be one of the reasons.
EDIT: I come with another short example, let us modify Jimmy with Timmy:
Michael Timmy Dolores
Remember the file2.txt looks like this:
Jimmy Jimmy Jimmy Jimmy Jimmy
Now if you run:
cat file1.txt | grep "Jimmy" > file2.txt
I just got myself with an empty file because of > instead of >> , there is no Jimmy in file1.txt.
Upvotes: 1
Reputation: 92986
Could be a buffering issue. stdout
is line buffered only if it goes to a character device. To check if this is the problem, call fflush(stdout)
manually after every printf
call. Make sure that the output buffer of stdout
is flushed correctly before your program terminates.
Upvotes: 1