文件I/O与标准I/O

时间:2022-05-30 14:12:23

返回值汇总:

文件I/O与标准I/O

printf的四种输出方式

1、遇到 \n 2、遇到scanf() 3、fflush(stdout) 4、缓冲区满

函数feof()

feof()函数可以检查到文件读写位置标记是否移到文件末尾,一句话概括就是判断文件有没有读完。读完了feof(fp)返回值为1,否则为0。

用文件I/O编写拷贝文件程序

代码:

/*****************************************************
File name:file_copy.c

Author: Tang Zhiqian

Date:2017-08-11 19:50
*****************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argv,char **argc) //命令行参数
{
printf("%s\n",argc[0]);
printf("%s\n",argc[1]);
printf("%s\n",argc[2]);

if (argv != 3) //判断输入是否合法
{
printf("please input the right command: ./a.out filename1 filename2\n");
return 1;
}
int fd1 = open(argc[1],O_RDONLY); //打开文件1,只读方式打开
if (-1 == fd1)
{
perror("open file1");
return 2;
}

int fd2 = open(argc[2],O_WRONLY | O_CREAT | O_APPEND); 打开文件2
if (-1 == fd2)
{
perror("open file2");
close(fd1);
return 3;
}

char buffer[1024]; //定义缓冲区
int count1 = 1;
while(count1)
{
count1 = read(fd1,buffer,1024); //返回值为实际读取的字节数
if (-1 == count1)
{
perror("read");
close(fd1);
close(fd2);
return 4;
}
int count2 = write(fd2,buffer,count1); //写入文件2
if (-1 == count2)
{
perror("write");
close(fd1);
close(fd2);
return 5;
}
}
close(fd1);
close(fd2);

return 0;
}

可以拷贝任何文件。

用标准I/O写拷贝文件程序

/*****************************************************
File name:copy_file.c

Author: Tang Zhiqian

Date:2017-08-13 09:34
*****************************************************/


#include <stdio.h>

#define MAX 1024

int main(int argc,char **argv)
{
if (3 != agrc)
{
printf("input:./a.out filename1 filename2\n");
return;
}
int fd1 = open(argv[1],O_RDONLY);
if (-1 == fd1)
{
perror("open file1");
return 1;
}

int fd2 = open(argv[2],O_RDWR | O_CREAT | O_APPEND);
if (-1 == fd2)
{
perror("open file2");
close(fd1);
return 2;
}
char buffer[MAX];
int count1 = 1
while(count1)
{
count1 = read(fd1,buffer,MAX);
if (-1 == count1)
{
perror("read");
close(fd1);
close(fd2);
return 3;
}

int count2 = write(fd2,buffer,count1);
if (-1 == count2)
{
perror("write");
close(fd1);
close(fd2);
return 4;
}
menset(buffer,0,MAX);
}

return 0;
}

跟文件I/O几乎一样。