设置O_APPEND标志和使用lseek函数的冲突雅验证

完成如下问题的猜想,并设计相应的程序验证自己的猜想:

当设定O_APPEND标志后,能否使用lseek函数修改当前文件偏移量?若能修改,读写操作发生在文件何处?

当设定O_APPEND标志后,可以否使用lseek函数修改当前文件偏移量,在使用lseek函数后文件偏移发生了改变。

读操作发生在修改后的文件偏移处

写操作发生在

#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (void)
{
    int fd =open ("test.txt", 0_RDWR : 0_APPEND);
    if(fd < 0){
    cout << "open error" <<endl;
    }
    //打开文件
    //获取文件fd

    char readBuf;
    readBuf = (char*) malloc (sizeof (char) *3) ;
    //设置read空间
    
    int pos =lseek (fd, B, SEEK_SET);
    cout <<"pos_1: " < <pos < <endl;
    //使用lseek修改问文件偏移

    read (fd,readBuf, 3) ;
    cout <<readBuf < <endl;
    //获得read结果

    write (fd, "test_0",strlen ("test_0") ) ;
    //获得write结果

    pos =lseek(fd, 1, SEEK_SET);
    cout<<"pos_2: "<<pos <<endl;
    write (fd, "test_1",strlen ("test_1") ) ;
    close (fd) ;
    return 0;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Sure, here's an example program that appends one file to another using the O_APPEND flag of open() and lseek(): ``` #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <source file> <destination file>\n", argv[0]); exit(EXIT_FAILURE); } int src_fd = open(argv[1], O_RDONLY); if (src_fd == -1) { perror("open"); exit(EXIT_FAILURE); } int dest_fd = open(argv[2], O_WRONLY | O_CREAT | O_APPEND, 0644); if (dest_fd == -1) { perror("open"); exit(EXIT_FAILURE); } off_t offset = lseek(dest_fd, 0, SEEK_END); if (offset == -1) { perror("lseek"); exit(EXIT_FAILURE); } char buf[BUFSIZ]; ssize_t nread; while ((nread = read(src_fd, buf, sizeof(buf))) > 0) { ssize_t nwritten = write(dest_fd, buf, nread); if (nwritten == -1) { perror("write"); exit(EXIT_FAILURE); } } if (nread == -1) { perror("read"); exit(EXIT_FAILURE); } if (close(src_fd) == -1) { perror("close"); exit(EXIT_FAILURE); } if (close(dest_fd) == -1) { perror("close"); exit(EXIT_FAILURE); } return 0; } ``` This program takes two command-line arguments: the source file to append and the destination file to append to. It opens the source file for reading and the destination file for writing with the O_APPEND flag, which ensures that all writes will be appended to the end of the file. It then seeks to the end of the destination file to get the current offset, reads from the source file in chunks and writes them to the destination file, and finally closes both files.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值