linux系统应用编程学习--标准IO

本文介绍了Linux系统应用编程中标准IO的特点,包括其缓存机制和可移植性,并通过实例展示了如何使用标准IO实现文件复制功能。此外,还提供了一个每隔1秒将时间戳写入日志文件的程序,演示了标准IO在实时记录和刷新数据方面的应用。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值