写入C中的输出文件

时间:2013-07-22 21:59:34

标签: c input fwrite

我在C中编写一个程序,它接受一个代表输出文件名称的命令行参数。然后我打开文件写入它。问题是,当我在命令行中写入内容时,它永远不会显示在我正在写入的文件中,并且文件中的任何文本都将被删除。这是我从stdin写入文件的代码。 (fdOut是指定的FILE * stream

 while(fread(buf, 1, 1024, stdin))
 {
   fwrite(buf, 1, 1024, fdOut);
 }

3 个答案:

答案 0 :(得分:2)

试试这段代码。

#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'停止输入。

答案 1 :(得分:0)

我们假设有stdin的数据,d.g。您使用的程序如下:

 cat infile.txt | ./myprog /tmp/outfile.txt

然后用fwrite()写入的数据将被缓冲,因此它不会在输出文件中出现 ,但仅在您的操作系统确定是时候刷新缓冲区时。 您可以使用

手动强制写入磁盘
 fflush(fdOut);

(可能你不想一直这样做,因为缓冲允许加速,特别是在写入慢速媒体时)

答案 2 :(得分:0)

size_t nbytes;
while ((nbytes = fread(buf, 1, 1024, stdin)) > 0)
{
    if (fwrite(buf, 1, nbytes, fdOut) != nbytes)
        ...handle short write...out of space?...
}

正如你所写的那样,你错误地处理了一个简短的阅读,写下了没有读到输出的垃圾。

相关问题