简单的写入一个文件以及从文件中读取输出:
#include<stdio.h>
mian()
{
int a[3]={100,200,300},a1[3]; //一份定义俩个变量将a读入文件,从文件中读取到a1
float b=123,45678,b1;
FILE *fp;
if((fp=fopen("data.txt","w"))==NULL)
{
perror("data.txt");
getch();
exit(0);
}
fwrite(&a,sizeof(a),1,fp);
fwrite(&b,sizeof(b),1,fp);
fclose(fp);//存入到文件中 (只能存一次)
if((fp=fopen("data.txt","r"))==NULL)
{
perror("data.txt");
getch();
exit(0);
}
fread(&a1,sizeof(a),1,fp);
fread(&b1,sizeof(b),1,fp);
fclose(fp);//从文件中读取
printf("a[3]= %d %d %d",a[0],a[1],a[2]);
printf("b: %f\n",b1);
getch();
return 0;
}
将一个文件中的每行的内容逆置:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char str[132],c;
long offset = 0,post1,post2;
int i,length=0;
if((fp=fopen("data.txt","r+")) == NULL)
{
perror("data.txt");
getch();
exit(0);
}
printf("start");
while(1)
{
post1=ftell(fp);
i=0;
while((c=fgetc(fp)=='\n' || c==EOF))
str[i++]=c;
str[i]='\0';
post2 = ftell(fp);
length = strlen(str);
strrev(str);
//for(i=0; i<length/2; i++){ c=str[i]; str[i]=str[lengh-1-i]; str[length-1-i]=t};
offset=post2-post1;
fseek(fp, -offset, SEEK_CUR);
fputs(str,fp);
fseek(fp,1,SEEK_CUR);
if(c==EOF) break;
fclose(fp);
printf("end.");
getch();
getch();
}
}
需要读取链表信息时,必须按原顺序逐个读取节点信息,然后重建链表
struct INFO *head = NULL,*p,*q;
int n=0;
FILE *fp;
if((fp = fopen("data.txt","r"))== NULL)
{
preeor("data.txt");
exit(0);
}
while(feof(fp))
{
p = (struct INFO*)malloc(sizeof(struct INFO))
fread(p,sizeof(struct INFO),1,fp);
if(n == 0)
head = p;
else
q->next = p;
q = p;
n++;
}
fclose(fp);