File.cpp函數定義文件:
#include<stdlib.h>
#include<stdio.h>
#include"File_Head.h"
int studentnum=2;
student stud[SIZE];


void File_fputc_fgetc()


{
FILE *fp;
char ch,filename[10];
scanf("%s",filename);
if((fp=fopen(filename,"w"))==NULL)

{
printf("cannot open file\n");
exit(0);
}
ch=getchar();
ch=getchar();
while(ch!='#')

{
fputc(ch,fp);
putchar(ch);
ch=getchar();
}

putchar(10);

fclose(fp);
}


void File_Cpy()


{
FILE *in=NULL,*out=NULL;
char ch,infile[10],outfile[10];
printf("Enter the infile name:\n");
scanf("%s",infile);
printf("Enter the outfile name:\n");
scanf("%s",outfile);

if((in=fopen(infile,"r"))==NULL)//若文件不存在不會新建。。。

{
printf("cannot open infile\n");
exit(0);
}

if((out=fopen(outfile,"w"))==NULL)//若文件不存在,則新建一個。。。

{
printf("cannot open outfile\n");
exit(0);
}

// while((ch=fgetc(in))!=EOF)//這個文件拷貝貌似好一點
// fputc(ch,out);

while(!feof(in))//用foef函數拷貝過來的文件末尾會多,ASC碼值為-1.(事實上ASC碼不可能等于-1)。。P336說明了feof更加優越不知道這里是怎么回事。。。

{
ch=fgetc(in);
fputc(ch,out);
putchar(ch);
}

fclose(in);
fclose(out);
}

//如果文件已二進制方式打開,fwrite和fread可以讀寫任何類型的信息
void File_write_read()


{

FILE *fp;
int i;

if((fp=fopen("stu_list","wb"))==NULL)//wb以二進制方式寫入文件

{
printf("cannot open file\n");
exit(0);
}

printf("enter number:\n");
scanf("%d",&studentnum);

printf("Enter students Imfor:\n");
for(i=0;i<studentnum;i++)//這里輸入的時候是以ASC碼的形式存入內存的,也就是已文本形式存入內存

{
scanf("%s %d %d %s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
}
for(i=0;i<studentnum;i++)

{
if(fwrite(&stud[i],sizeof(student),1,fp)!=1)//向fp所指向的文件以二進制的形式寫入sizeof(student)大小的內容,內容為地址stud[i]
printf("file write error\n");
}
// rewind(fp);
fclose(fp);

fp=fopen("stu_list","rb");
for(i=0;i<studentnum;i++)

{
fread(&stud[i],sizeof(student),1,fp);//從fp所指向的文件中以二進制的形式讀出sizeof(student)大小的字節數,將起放入stud[i]中
printf("%-10s %4d %4d %-15s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
//已ASC碼的形式輸出。。
}

fclose(fp);
}

void load()


{
FILE *fp;
int i;
if((fp=fopen("stu_dat","rb"))==NULL)

{
printf("cannot open infile\n");
return;
}
for(i=0;i<studentnum;i++)

{
if(fread(&stud[i],sizeof(student),1,fp)!=1)

{
if(feof(fp))

{
fclose(fp);
return;
}
}
}
printf("file read error\n");

fclose(fp);
}

void File_fseek()


{
int i;
FILE *fp=NULL;
if((fp=fopen("stu_list","rb"))==NULL)

{
printf("can not open file\n");
exit(0);
}

for(i=0;i<10;i+=2)

{
fseek(fp,i*sizeof(student),0);//位置指針重置
fread(&stud[i],sizeof(student),1,fp);
printf("%s %d %d %s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}

fclose(fp);
}
posted on 2010-11-01 22:25
jince 閱讀(243)
評論(0) 編輯 收藏 引用