Linux C 语言中fread()与fwrite()用法


我并没有研究过fread()与fwrite()这两个函数的具体实现,但是在使用中发现一些小细节。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#define maxsize 1000
int main(int argc ,char *argv[])
{
 FILE *fp1,*fp2;
 char ch[maxsize];
 int m,n;
 int base,end;
 if(argc!=3)
 {
  printf("command error!\n");
  return -1;
 }
 if((fp1=fopen(argv[1],"r"))==NULL)
 {
  printf("file %s cannot open",argv[1]);
  return -1;
 }
 if((fp2=fopen(argv[2],"w+"))==NULL)
 {
  printf("cannot creat file %s",argv[1]);
  return -1;
 }
 base=ftell(fp1);
 m=fread(ch,8,3,fp1);
 printf("%s\n",ch);
 end=ftell(fp1);
 n=fwrite(ch,8,m,fp2);
// n=fwrite(ch,end-base,1,fp2);
 fprintf(stdout,"m=%d,n=%d\n",m,n);
 fclose(fp1);
 fclose(fp2);
 return 0;
}
在程序2.c中有下面几行:file1为原文件,程序实现文件的复制。
m=fread(ch,8,3,fp1);
n=fwrite(ch,8,m,fp2);
fprintf(stdout,"m=%d,n=%d\n",m,n);
执行./2 file1 file2(2为编译后的程序名字),发现输出m=0,n=0.file1内容为123456.
原因为file1中只有6个字符,不够8个,而fread是以8个字符为单位进行读取的(7个也可以,自动加一个'\n'),
所以m=n=0,但是加上printf("%s\n",ch);后,程序正常输出123456.说明file1中 的内容已经被正确复制进ch数组。
但是仍然以8为单位进行写入会失败。
此时调用ftell(fp1)函数进行定位,虽然m=fread(ch,8,3,fp1);读取失败,但是file1中的文件位置指针还是移动了的,只是
到了尾部仍然没有达到8个字符。
此时改成:n=fwrite(ch,end-base,1,fp2);就会正确写入。

相关内容