【问题标题】:C program of accessing device file don't work访问设备文件的C程序不起作用
【发布时间】:2018-02-04 03:53:38
【问题描述】:

我见过device file can be accessed directly in Linux,我想试一试。我有一个没有任何文件系统的空闲磁盘分区。我的测试代码如下。 我希望在第二次运行程序时得到输出read data: 199。但实际上,我得到了两次输出read data: 0。程序期间没有出现错误。我不知道哪里错了。
谢谢你的时间。

测试代码:

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

int main(){
    int num = 0;
    int fd = open("/dev/sda6", O_RDWR);

    if(fd == -1){
        fprintf(stderr, "open device failed, errno : %s(%d) \n", 
            strerror(errno), errno);
        return 1;
    }

    ssize_t ret = read(fd, &num, sizeof(int));
    if(ret != sizeof(int)){
        fprintf(stderr, "read fails, errno : %s(%d) \n", 
            strerror(errno), errno);
        return 1;
    }
    printf("read data: %d\n", num);

    num = 199;
    ret = write(fd, &num, sizeof(int));
    if(ret != sizeof(int)){
        fprintf(stderr, "write fails, errno : %s(%d) \n", 
            strerror(errno), errno);
        return 1;
    }
    close(fd);

    return 0;
}

【问题讨论】:

    标签: c linux


    【解决方案1】:

    readwrite 在描述符中存储的隐式文件偏移处开始读/写,并以读/写的字节数递增。因此,您现在将读取字节 0 .. 3,然后写入字节 4 .. 7。

    不要使用readwrite 并与lseek 等混淆,请使用POSIX 标准pread and pwrite,它不使用描述符中的隐式文件偏移,而是采用显式文件调用中文件开头的偏移量。

    #include <unistd.h>
    ssize_t pread(int fd, void *buf, size_t count, off_t offset);
    ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
    

    ...

    ssize_t ret = pread(fd, &num, sizeof(int), 0);
    ssize_t ret = pwrite(fd, &num, sizeof(int), 0);
    

    【讨论】:

      【解决方案2】:

      你没有在你的程序中seek,所以它的作用是: 读取设备的前 4 个字节,然后写入后 4 个字节。

      试试

      lseek(fd,0,SEEK_SET);
      

      如果你想在 fole 开头写的话,在写之前。

      【讨论】:

        猜你喜欢
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 2012-02-22
        • 1970-01-01
        • 2016-04-23
        • 2017-02-24
        • 1970-01-01
        相关资源
        最近更新 更多