linux系统应用编程学习–标准IO
1,与文件IO的区别:
a,标准IO是带缓存的IO操作。
b,源代码不需要任何修改就可以在其他操作系统下编译运行,具有更好的可移植性.
c,使用标准I/O可以减少系统调用的次数,提高系统效率
2, 主要API
3,练习:编写一个cp命令实现文件复制:1-my_cp2.c
#include <stdio.h>
#define MAX_SIZE 128
int main(int argc,char *argv[])
{
FILE *fd1,*fd2;
char buf[MAX_SIZE];
if(argc !=3){
printf("cmd error!\n");
return -1;
}
if( (fd1=fopen(argv[1],"r")) == NULL ){
printf("open source file error!\n");
return -1;
}
if( (fd2=fopen(argv[2],"w+")) == NULL){
printf("open/create dist file error!\n");
return -1;
}
while( fgets(buf,MAX_SIZE,fd1) != NULL){
if( fputs(buf,fd2) == EOF){
printf("wirte error!\n");
}
}
fclose(fd1);
fclose(fd2);
printf("cp execute finish\n");
}
编译
$ gcc ./1-my_cp2.c -o ./1-my_cp2
运行:将源文件1-my_cp2.c 复制到新文件中my_cp2_file
$ ./1-my_cp2 ./1-my_cp2.c ./my_cp2_file
查看结果与源文件相同
$ cat ./my_cp2_file
4,练习2:间隔1秒将时间戳打印到log文件中
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
FILE *fd;
time_t tm;
if( argc !=2)
printf("cmd eror!\n");
if( (fd =fopen(argv[1],"a+")) ==NULL){
printf("open file fail!\n");
}
printf("enter while\n");
while(1){
time(&tm);
fputs(ctime(&tm),fd);
//fprintf(fd,"%s",ctime(&tm)); //also OK
fflush(fd);
sleep(1);
printf("is running...\n");
}
fclose(fd);
}
gavin@vm-ubuntu:~/2exercise/1-stdIO$ gcc ./4-log.c -o 4-log
gavin@vm-ubuntu:~/2exercise/1-stdIO$ ./4-log log_file
enter while
is running...
is running...
is running...
is running...
is running...
^Z
[6]+ Stopped ./4-log log_file
gavin@vm-ubuntu:~/2exercise/1-stdIO$ cat ./log_file
Sun Aug 15 09:21:31 2021
Sun Aug 15 09:21:32 2021
Sun Aug 15 09:21:33 2021
Sun Aug 15 09:21:34 2021