繁体   English   中英

使用C中的读取功能从文件中读取前5个字符

[英]Reading first 5 characters from a file using fread function in 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);
}

当我输入任何示例文件名时..it打印文件的所有数据。

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

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);

祝好运!

PS

为了在评论中回答您的问题, fread允许我们以“原子单位”读取数据,因此,如果无法使用整个单位,则不会读取任何数据。

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

您可以使用fread(&ch,1,10,fp)读取10个单位fread(&ch,1,10,fp)也可以使用int i; fread(&i,sizeof(int),1,fp);读取单个二进制int所有未返回字节(这不会移植-这只是一个演示) int i; fread(&i,sizeof(int),1,fp); int i; fread(&i,sizeof(int),1,fp);

在这里阅读更多。

这是您代码的修改版本。 在修改的行中检查注释

#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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM