【问题标题】:Interpreting data from fread()解释来自 fread() 的数据
【发布时间】:2014-02-06 02:32:06
【问题描述】:

所以我试图通过我的代码传递一个.txt 文件,让它将字符单独回显到输出中。我正在运行脚本

./a.out < testWords.in > myOut.out

关键就在这里:

size_t bytes = fread(buffer. sizeof(char),sizeof(char),stdin);
fwrite(buffer,sizeof(char),bytes,stdout);
fflush(stdout);

效果很好。

但是如何在 if 语句中逐一解释字符?例如

if (bytes == '\n')

不会在换行时触发。

编辑:

getc(stdin) 是一种更有效的方式来完成我的任务。

【问题讨论】:

  • bytes 不包含您读取的数据;你会在buffer[0] 中找到它。由于您一次只阅读一个字符,您不妨使用getchargetc;同样你可以使用putcharputc
  • fread(buffer, sizeof(char),sizeof(buffer),stdin);
  • getc 是一种更有效的方法,谢谢 Keith Thompson。
  • 这不仅仅是“更高效”。您尝试使用 fread 从文本文件中读取单个字符的事实表明您甚至没有阅读过关于 C 的书的单个章节。阅读一本书(最终是许多书)是您可能的唯一方法学习语言。细节不能被灌输。

标签: c stdout stdin fwrite fread


【解决方案1】:

我不知道如何定义效率,但是如果您fread() 一个大缓冲区,您的代码可能会运行得更快。请参阅 @BLUEPIXY 的行。另见speed comparison between fgetc/fputc and fread/fwrite in C

你的if (bytes == '\n') 行很奇怪,因为像素在buffer...bytes 只是成功读取的元素数。我确定您的意思是 if(buffer[i]=='\n')

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int count=0;
    int i;
    char buffer[1000];
    size_t bytes=1;
    while(bytes!=0){
        bytes = fread(buffer, sizeof(char),sizeof(buffer),stdin);

        for(i=0;i<bytes;i++){
            if(buffer[i]=='\n'){
                count++;
            }
        }
        fwrite(buffer,sizeof(char),bytes,stdout);
        fflush(stdout);
    }
    printf("there were %d lines in your file\n",count);
    return 0;
}

我也很确定我的回答来得太晚了!

再见,

弗朗西斯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多