文件读写io操作范例

时间:2023-02-23 15:36:08

系统io读写,copy

int main(int argc, char **argv)

{  if(argc != 3)

{   printf("Usage: %s <src> <dst>\n", argv[0]);

exit(0);

}

int fd1, fd2;  fd1 = open(argv[1], O_RDONLY);

fd2 = open(argv[2], O_CREAT | O_TRUNC | O_WRONLY);

if(fd1 == -1 || fd2 == -1)  {   perror("open() failed");   exit(0);  }

char buf[100];

int nread;

while(1)

{   bzero(buf, 100);   nread = read(fd1, buf, 100);

if(nread == 0) // hits the end of file

{    break;

}   if(nread == -1)

{    perror("read() failed");

exit(0);

}

write(fd2, buf, nread);  }

close(fd1);  close(fd2);

return 0; }

标准io读写操作.........................

fopen-----------------------------------------------------------------fclose范例:

int main(int argc, char **argv) {

if(argc != 3)  {

printf("Usage: %s <src> <dst>\n", argv[0]);

exit(0);

}

FILE *fp1 = fopen(argv[1], "r");

if(fp1 == NULL)  {

fprintf(stderr, "fopen(%s) failed: %s\n",     argv[1], strerror(errno));

exit(0);

}

FILE *fp2 = fopen(argv[2], "w");  if(fp2 == NULL)  {

fprintf(stderr, "fopen(%s) failed: %s\n",     argv[2], strerror(errno));

exit(0);

}

char *buf = calloc(5, 20);

int nread, nwrite;

while(1)  {   long begin = ftell(fp1);

nread = fread(buf, 20, 5, fp1); // n是真正读取到的数据块个数 n<=5          // 100 --> 5          // 98  --> 4          // 80  --> 4          // 21  --> 1          // 19  --> 0          // 1  --> 0

if(nread == 5) // 正常读取

{    char *p = buf;

while(nread > 0)    {

nwrite = fwrite(p, 20, nread, fp2); // nwrite <= n

nread -= nwrite;

p += nwrite*20;    }

}

else if(nread >= 0) // 到达文件尾部

{    long end = ftell(fp1);

fwrite(buf, end-begin, 1, fp2);

break;

}

else // 读取出错了

{    perror("fread() failed");

fclose(fp1);

fclose(fp2);

exit(0);

}  }

fclose(fp1);

fclose(fp2);

return 0; }

fgets--------------------------------------------------------------------fputs范例:

while(1)  {

char *tmp = fgets(buf, 20, fp1); // 从fp1读取一行(最多19字节)放到buf中

if(tmp == NULL)   {

// 1. 遇到了错误

if(ferror(fp1))    {

perror("fgets() failed");

break;

}

// 2. 遇到了文件尾

if(feof(fp1))

{     printf("copy completed.\n");

break;

}

}

fputs(buf, fp2);

}

fgetc----------------------------------------------------------------fputc

while(1)  {   ch = fgetc(fp1);

if(ch == EOF)

{    // 1. 遇到错误

if(ferror(fp1))

{     perror("fgetc() failed");

break;    }

// 2. 遇到文件尾

if(feof(fp1))    {

printf("copy completed.\n");

break;    }

}

fputc(ch, fp2);

}