使用C中的fread函数从文件中读取前5个字符

时间:2016-03-08 14:55:25

标签: c

如何使用fread功能从示例txt文件中读取5到10个字符。 我有以下代码:

#include <stdio.h>        

main() 
{    

    char ch,fname[20];

    FILE *fp;
    printf("enter the name of the file:\t");
    gets(fname);
    fp=fopen(fname,"r");

    while(fread(&ch,1,1,fp)!=0)
        fwrite(&ch,1,1,stdout);

    fclose(fp);
}

当我输入任何样本文件名时..打印文件的所有数据。

我的问题是如何只打印样本文件中的前5到10个字符。

2 个答案:

答案 0 :(得分:3)

你的while循环运行直到read到达文件末尾(第一次读取0字节)。

您需要使用for循环或计数器来更改条件。

即。 (这些是建议,而不是完整的工作代码):

int counter = 10;

while(fread(&ch,1,1,fp)!=0 && --counter)
    fwrite(&ch,1,1,stdout);

int i;
for(i=0; i < 10 && fread(&ch,1,1,fp) > 0 ; i++)
    fwrite(&ch,1,1,stdout);
祝你好运!

P.S。

要在评论中回答您的问题,fread允许我们以“原子单位”读取数据,这样如果整个单位不可用,则不会读取任何数据。

单个字节是最小单位(1),并且您正在读取一个单位(单个字节),这是1,1中的fread(&ch,1,1,fp)部分。

您可以使用fread(&ch,1,10,fp)读取10个单位,或者使用int int i; fread(&i,sizeof(int),1,fp);(这不是可移植的 - 只是一个演示版)的所有字节p>

了解更多here

答案 1 :(得分:1)

以下是您的代码的修改版本。检查修改行的注释

#include <stdio.h>        

#define N_CHARS 10  // define the desired buffer size once for code maintenability

int main() // main function should return int
{    
    char ch[N_CHARS + 1], fname[20]; // create a buffer with enough size for N_CHARS chars and the null terminating char 

    FILE *fp;
    printf("enter the name of the file:\t");
    scanf("%20s", fname); // get a string with max 20 chars from stdin        

    fp=fopen(fname,"r");

    if (fread(ch,1,N_CHARS,fp)==N_CHARS) { // check that the desired number of chars was read
        ch[N_CHARS] = '\0'; // null terminate before printing    
        puts(ch);            // print a string to stdout and a line feed after
    }

    fclose(fp);
}