Linux系统编程—文件编程(补充)

在上一篇博客中我们了解了Linux中关于文件的常用api及其用法
在本篇博客中我们将对这些api进行进一步运用

实现cp()函数功能

在Linux系统的vim编辑器中有一个用于文件复制的api :cp();
例如我们在vim编辑器中创立一个文件vi demo1.c
在demo1.c中写入一段代码再使用cp函数

cp demo1.c demo2.c

这样demo1.c 中的内容就被复制到demo2.c中了

基本编程思想
1,打开Src文件
2,读Src到buf缓冲区
3,打开/创建Des
4,将buf缓冲区的数据写入Des
5,close两个文件

vim界面

vi demo1.c
gcc demo1.c -o mycp
./mycp ./demo2.c
//则将demo1.c拷贝到了demo2.c
#include <sys/types.h>
#include <sys/stst.h>
#include <fcantl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char **argv)
//argc:字符串数组长度,argv:字符串数组
{
    int fdSrc;
    int fdDes;
    char *readBuf = NULL;
    if(argc != 1){  
     printf("error!\n")
     exit(-1);
    }
    fdSrc = open(argv[1],O_RDWR);
    int a = lseek(fdSrc,0,SEEK_END);
    readBuf = (char *)malloc(sizeof(char)*a + 8);//防止内存不够用
    int n_read = read(fdSrc, readBuf, a);
    lseek(fdSrc,0,SEEK_SET);
    fdDes = open(argv[2],O_RDWR|O_CREAT,0600);
    int n_write = write(fdDes,readBuf,strlen(readBuf));
    close(fdSrc);
    close(fdDes);
}

写不同类型的数据进文件

在之前所有的练习应用中,我们对文件的操作都是基于字符串,那么如何对其他类型的文件进行操作呢?

写整数到文件

在定义了char类型的指针为文件的缓冲区时,我们要写入一个整形数

#include <sys/types.h>
#include <sys/stst.h>
#include <fcantl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    int fd;
    int data = 100;
    int data2 = 0;
    fd = open("./file1",O_RDWR);
    int n_write = write(fd, &data, sizeof(int));
    lseek(fd,0,SEEK_SET);
    int n_read = read(fd, &data2, sizeof(int));
    int n_write = write(fdDes,readBuf,strlen(readBuf));
    close(fd);
    return 0;
}

写结构体到文件

#include <sys/types.h>
#include <sys/stst.h>
#include <fcantl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
   int a;
   char b;
};
int main()
{
    int fd;
    struct Test data[2] = {{100,'a'},{200,'b'}};
    struct Test data2 [2];
    fd = open("./file1",O_RDWR);
    int n_write = write(fd, &data, sizeof(struct Test)*2);
    
    lseek(fd,0,SEEK_SET);
    
    int n_read = read(fd, &data2, sizeof(struct Test)*2);
    printf("read %d,%c\n",data2[0].a,data2[0].b);
    printf("read %d,%c\n",data2[1].a,data2[1].b);
    close(fd);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值