解释来自fread()的数据

时间:2014-02-06 02:32:07

标签: c stdout stdin fwrite fread

所以我试图通过我的代码传递.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)是一种更有效的方法来完成我的任务。

1 个答案:

答案 0 :(得分: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;
}

我也很确定我的答案为时已晚,无法发挥作用!

再见,

弗朗西斯

相关问题