Reputation: 195
I am writing a program in C that takes a a command line argument that represents the name of an output file. I then opened the file to write to it. The problem is that when I write something in the command line, it never shows up in the file I was writing to and any text in the file is erased. Here is the code I have for writing to the file from stdin.
(fdOut
is the FILE * stream
that was specified)
while(fread(buf, 1, 1024, stdin))
{
fwrite(buf, 1, 1024, fdOut);
}
Upvotes: 0
Views: 1199
Reputation: 2857
try this code.
#include "stdio.h"
int main()
{
char buf[1024];
FILE *fdOut;
if((fdOut = fopen("out.txt","w")) ==NULL)
{ printf("fopen error!\n");return -1;}
while (fgets(buf, 1024, stdin) != NULL)
{
// int i ;
// for(i = 0;buf[i]!=NULL; ++i)
// fputc(buf[i],fdOut);
fputs(buf,fdOut);
// printf("write error\n");
}
fclose(fdOut);
return 0;
}
Note : use Ctrl+'D' to stop input.
Upvotes: 2
Reputation: 755084
size_t nbytes;
while ((nbytes = fread(buf, 1, 1024, stdin)) > 0)
{
if (fwrite(buf, 1, nbytes, fdOut) != nbytes)
...handle short write...out of space?...
}
As you wrote it, you mishandle a short read, writing garbage that was not read to the output.
Upvotes: 0
Reputation: 31404
let's assume that there is data coming in at stdin
, d.g. you are using your program like:
cat infile.txt | ./myprog /tmp/outfile.txt
then data written with fwrite()
will be buffered, so it won't appear immediately in the output file, but only when your OS decides that it's time to flush the buffer.
you can manually force writing to disk by using
fflush(fdOut);
(probably you don't want to do this all the time, as buffering allows for great speedups, esp when writing to slow media)
Upvotes: 0