[英]Reading first 5 characters from a file using fread function in C
How do i read some 5 to 10 characters from a sample txt file using an fread funtion. 如何使用fread函数从示例txt文件读取一些5到10个字符。 I have the following code: 我有以下代码:
#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);
}
when i enter any sample filename..it prints all the data of the file. 当我输入任何示例文件名时..it打印文件的所有数据。
my question is how to print only the first 5 to 10 characters from the sample file. 我的问题是如何只打印示例文件中的前5到10个字符。
Your while loop runs until read
reaches the end of the file (reads 0 bytes for the first time). while循环将一直运行,直到read
到达文件末尾(第一次读取0个字节)。
You will want to change the condition by using a for
loop or a counter. 您将需要使用for
循环或计数器来更改条件。
ie (these are suggestions, not the full working code): 即(这些是建议,而不是完整的工作代码):
int counter = 10;
while(fread(&ch,1,1,fp)!=0 && --counter)
fwrite(&ch,1,1,stdout);
or 要么
int i;
for(i=0; i < 10 && fread(&ch,1,1,fp) > 0 ; i++)
fwrite(&ch,1,1,stdout);
Good luck! 祝好运!
PS PS
To answer your question in the comments, fread
allows us to read the data in "atomic units", so that if a whole unit isn't available, no data will be read. 为了在评论中回答您的问题, fread
允许我们以“原子单位”读取数据,因此,如果无法使用整个单位,则不会读取任何数据。
A single byte is the smallest unit (1), and you are reading one unite (of a single byte), this is the 1,1
part in the fread(&ch,1,1,fp)
. 单个字节是最小单位(1),并且您正在读取一个字节(单个字节),这是fread(&ch,1,1,fp)
的1,1
部分。
You could read 10 units using fread(&ch,1,10,fp)
or read all the bytes unrequited for a single binary int
(this won't be portable - it's just a demo) using int i; fread(&i,sizeof(int),1,fp);
您可以使用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);
Here is a modified version of your code. 这是您代码的修改版本。 Check the comments at the lines that are modified 在修改的行中检查注释
#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.