[英]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.