|
文件操作相关的
//try fread/fwrite function
#include <stdio.h>
#include <sys/stat.h>
#define BUFSIZE 4
#define FNAMELEN 80
void main()
{FILE *fp1,*fp2;
char filebuf[BUFSIZE],filename[FNAMELEN];;
int filelen,filecount,toread,i;
struct stat pstat;
/*用户输入文件路径和名程:
printf("lease input the path and name of the file you want to copy from:\n");
scanf("%s",filename);getchar();
if(fp1=fopen(filename,"r")==NULL){
printf("open file error\n");
exit(1);
}
printf("filename:%s\n",filename);*/
if((fp1=fopen("tryfile","r"))==NULL){printf("can't open tryfile\n");exit(0);}
if (stat("tryfile",&pstat) == -1) {//??
printf("stat file error\n");
exit(1);
}
filelen=pstat.st_size;
filecount=filelen/BUFSIZE;
if(filelen%BUFSIZE!=0)filecount++;
printf("filelen:%d\nfilecount:%d\n",filelen,filecount);
if((fp2=fopen("tryfilecp","w"))==NULL){printf("can't open tryfilecp\n");exit(0);}
for(i=0;i<filecount;i++){printf("try pt:fread %d\n",i);/*读取 写本地文件*/
if(i+1==filecount)toread=filelen-i*BUFSIZE;
else toread=BUFSIZE;
if(fread(filebuf,toread*sizeof(char),1,fp1)!=1){printf("read file error!\n");exit(1);}
printf("try pt:fread %d\n",i);
if(fwrite(filebuf,toread*sizeof(char),1,fp2)!=1){printf("write file error!\n");
exit(1);}
printf("try pt:fwrite %d\n",i); }
fclose(fp1);printf("try pt:fclose fp1!\n");
fclose(fp2);printf("try pt:fclose fp2!\n");
}
程序中指明文件可以读取,复制;而接受用户输入文件路径和名称而读写文件出错,但是文件名称、长度等信息是正确的,就是执行到读文件那一步出现“段错误”而退出!请指教,该如何完成用户输入文件路径和名程功能?
另外,貌似fread/fwrite是否必须读取/写入指定长度,否则出错!?比如,我指定读4个字节,而文件中有5个字符,再加最后的“\0”,共计六个字符,读取时会出错。所以我在循环读写文件那一段加了toread以解决最后一次读写不为指定值的问题,运行通过!
现在问题在于,接受用户输入文件路径和名称而读写文件出错,但是文件名称、长度等信息是正确的,就是执行到读文件那一步出现“段错误”而退出!
没有缩进什么的,比较乱,个位见谅,费神!
谢谢! |
|