我正在用 C 语言编写一个程序,它接受一个表示输出文件名称的命令行参数。然后我打开文件写入它。问题是当我在命令行中写东西时,它永远不会出现在我正在写入的文件中,并且文件中的任何文本都被删除。这是我从标准输入写入文件的代码。(fdOut
是FILE * stream
指定的)
while(fread(buf, 1, 1024, stdin))
{
fwrite(buf, 1, 1024, fdOut);
}
试试这个代码。
#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;
}
注意:使用 Ctrl+'D' 停止输入。
让我们假设有数据进来stdin
,dg 你正在使用你的程序,比如:
cat infile.txt | ./myprog /tmp/outfile.txt
然后写入的数据fwrite()
将被缓冲,因此它不会立即出现在输出文件中,但只有当您的操作系统决定是时候刷新缓冲区时才会出现。您可以使用手动强制写入磁盘
fflush(fdOut);
(可能你不想一直这样做,因为缓冲可以提高速度,尤其是在写入慢速媒体时)
size_t nbytes;
while ((nbytes = fread(buf, 1, 1024, stdin)) > 0)
{
if (fwrite(buf, 1, nbytes, fdOut) != nbytes)
...handle short write...out of space?...
}
当你写它时,你错误地处理了一个短读,写了没有读到输出的垃圾。