read/write file
1387 ワード
操作フォルダ
2)
#include
int main(void)
{
char filename[100];
static int num=1;
snprintf(filename,100,"day_%d",num);
FILE* fp;
fp = fopen(filename,"rb");
if(!fp){
printf("error open fp
");
}
fseek(fp,20,SEEK_SET);
//fseek(fp,0,SEEK_END);
int len = ftell(fp);
char buffer[100];
fseek(fp,0,SEEK_SET);
fread(buffer,len,1,fp);
fclose(fp);
FILE* fp_r;
fp_r = fopen("day","w");
if(!fp_r){
printf("error open fp_r
");
}
fwrite(buffer,len,1,fp_r);
fclose(fp_r);
return 0;
}
2)
int main(int argc, char* argv[])
{
char *read = (char *)malloc(100);
FILE *fp;
fp = fopen("a.txt","a+");//contain "Julie"
if(fp == NULL)
printf("fopen error
");
//fread related with the fp location
fseek(fp,0,SEEK_SET);
if(fread(read,5,1,fp)!=1)
printf("fread error
");
sprintf(read+5,"%.14s","love me tender");
int len = ftell(fp);
if(len){
printf("now the length is %d
",len);
fseek(fp,0,SEEK_END);
}
//fwrite not related with fp location
if(fwrite(read,strlen(read),1,fp)!=1)
printf("fwrite failed
");
printf("%s",read);
printf("
");
fclose(fp);
return 0;
}