#include <stdio.h>
void main()
{
char s[255];
int i;
int bytesNumber;
FILE *fp;
fp=fopen("test.txt", "r");
fgets(s, 255, fp);
printf("1:%s\n", s);
fgets(s, 255, fp);
printf("2:%s\n", s);
fgets(s, 255, fp);
printf("3:%s\n", s);
fscanf(fp, "%s", s);
printf("4:%s\n",s);
printf("input a intger:");
scanf("%d",&bytesNumber);
printf("now read bytes:");
fscanf(fp, "%d", &bytesNumber);
printf("bytes is %d", bytesNumber);
for( i=1; i<=9; i++)
{
fscanf(fp, "%d", &bytesNumber);
printf("\tbytes%d:%d",i,bytesNumber);
}
printf("\tAnother bytes is %d\n", bytesNumber);
fgets(s, 255, fp);
printf("Read complete.\n");
fclose(fp);
}
遍历文件
#include <stdio.h>
void main()
{
char s[255];
int i;
FILE *fp;
fp=fopen("test.txt", "r");
i=1;
while (fgets(s, 255, fp))
{
printf("%d:%s\n", i,s);
i++;
}
printf("Read complete.\n");
fclose(fp);
}
test.txt 内容为
first line
second line
third line
forth 1 2 3 4 5 6 7 8 9 10 11 12 13
输出结果为
1:first line
2:second line
3:third line
4:forth
input a intger:1111111111
now read bytes:bytes is 1 bytes1:2 bytes2:3 bytes3:4
bytes4:5 bytes5:6 bytes6:7 bytes7:8 bytes8:9
bytes9:10 Another bytes is 10
Read complete.
参考: