C语言 文件操作,要读取一个txt文件内容

文件每行的格式都相同,如果要随机读取,比如第一次产生的随机数定位在第五行,那么把第五行所有的内容输出,问题就是如何控制输出为第五行呢?
最新回答
初夏の晨曦

2024-05-03 00:15:23

在C语言中,文件操作都是由库函数来完成的。
要读取一个txt文件,首先要使用文件打开函数fopen()。
fopen函数用来打开一个文件,其调用的一般形式为: 文件指针名=fopen(文件名,使用文件方式) 其中,“文件指针名”必须是被说明为FILE 类型的指针变量,“文件名”是被打开文件的文件名。 “使用文件方式”是指文件的类型和操作要求。“文件名”是字符串常量或字符串数组。
其次,使用文件读写函数读取文件。
在C语言中提供了多种文件读写的函数:
·字符读写函数 :fgetc和fputc
·字符串读写函数:fgets和fputs
·数据块读写函数:freed和fwrite
·格式化读写函数:fscanf和fprinf
最后,在文件读取结束要使用文件关闭函数fclose()关闭文件。

下面以格式化读写函数fscanf和fprintf为例,实现对文件A.txt(各项信息以空格分割)的读取,并将它的信息以新的格式(用制表符分割各项信息)写入B.txt,实现对A.txt的处理。

C语言源程序如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct student{
char name[32];
int no;
char sex[16];
float score;
} stu;

int main(int argc, char* argv[])
{
//打开文件
FILE * r=fopen("A.txt","r");
assert(r!=NULL);
FILE * w=fopen("B.txt","w");
assert(w!=NULL);

//读写文件
stu a[128];
int i=0;
while(fscanf(r,"%s%d%s%f",a[i].name,&a[i].no,a[i].sex,&a[i].score)!=EOF)
{
printf("%s\t%d\t%s\t%g\n",a[i].name,a[i].no,a[i].sex,a[i].score);//输出到显示器屏幕
fprintf(w,"%s\t%d\t%s\t%g\n",a[i].name,a[i].no,a[i].sex,a[i].score);//输出到文件B.txt
i++;
}

//关闭文件
fclose(r);
fclose(w);

system("pause");
return 0;
}
ㄍ安于此生

2024-05-03 03:47:20

//data.txt文件内容如下

1 个 猪
2 个 猪
3 个 猪
4 个 猪
5 个 猪
6 个 猪
7 个 猪
8 个 猪

//运行结果一
the 8 line :8 个 猪

Press any key to continue
//运行结果二
out of range!
Press any key to continue

//代码如下
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main(void)
{
int lid,cnt=0,flag=0;;
char buf[100]="\0";
FILE *fp;

srand((unsigned)time(NULL));
fp=fopen("data.txt","r");
lid= rand()%10+1;
while (fgets(buf,99,fp)!=NULL)
{
if(cnt==lid)
{
printf("the %d line :%s\n",lid+1,buf);
flag=1;
break;
}
cnt++;
}
if (flag==0)
{
printf("out of range!\n");
}
}
舟遥客

2024-05-03 00:56:13

fseek 可以改变数据指针的位置
恃宠拢权

2024-05-03 00:33:11

#include<stdio.h>

FILE*stream;

void main(void)
{
long l;
float fp;
char s[81];
char c;

stream=fopen("fscanf.out","w+");
if(stream==NULL)
printf("Thefilefscanf.outwasnotopened\n");
else
{
fprintf(stream,"%s%ld%f%c","hello world",
65000,3.14159,'x');

/*Setpointertobeginningoffile:*/
fseek(stream,0L,SEEK_SET);

/*Readdatabackfromfile:*/
fscanf(stream,"%s",s);
fscanf(stream,"%ld",&l);

fscanf(stream,"%f",&fp);
fscanf(stream,"%c",&c);

/*Outputdataread:*/
printf("%s\n",s);
printf("%ld\n",l);
printf("%f\n",fp);
printf("%c\n",c);

fclose(stream);
}
}