C 系统调用 — 不断收到 lseek 和 read 的错误



这是我正在为课堂做的练习,我不明白为什么这不会运行......

尝试从变量 (num2( 分配长度的字符数组(缓冲区(时遇到问题。

您可以像这样执行该文件:

./file.c offset numOfChars filename.txt
./file.c 4 10 somefile.txt

如果某个文件包含文本:

为什么这个 c 程序不起作用。 我想不通

程序应打印

这不是吗

这是代码:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
main(int ac, char *av[]){
    // Save the command line variables
    int num1 = av[1];
    int num2 = av[2];
    long numbyte1 = av[1];
    long numbyte2 = av[2];
    int fd = open(av[3], O_RDONLY);
    // Try to open the file
    if( fd < 0 )
        perror(fd + " - Could not open file!");
    // use stat to get file size
    struct stat sb;
    if(fstat(fd,&sb) < 0)    
        return 1;
    // Check to see if the file is big enough for the provided offset
    if(sb.st_size < num1+num2){
        perror(fd + " - Size of file is not large enough for provided offset!" + fd);
    }
    char buffer[num2];
    if(lseek(fd, numbyte1 ,SEEK_SET) < 0) return 1;
    if(read(fd, buffer, numbyte2) != numbyte2) return 1;
    printf("%sn", buffer);
    return 0;
}

我看到的问题:

  1. ./file.c不是运行程序的正确方法。您需要编译程序并创建可执行文件。然后,您可以运行它。

    如果您有gcc,请使用:

    gcc -o file -Wall file.c
    ./file 4 10 somefile.txt
    
  2. 这些线条

    int num1 = av[1];
    int num2 = av[2];
    

    不对。编译器应报告警告。使用 gcc ,我收到这两行的以下警告:

    soc.c:在函数"main"中:Soc.C:4:15:警告:初始化使指针成为整数而不进行强制转换 [默认启用]int num1 = av[1];           ^Soc.C:5:15:警告:初始化使指针成为整数而不进行强制转换 [默认启用]int num2 = av[2];

    av[1]av[2]属于 char* 型。如果包含整数,则可以使用标准库中的多个函数之一从中提取整数。例如

    int num1 = atoi(av[1]);
    int num2 = atoi(av[2]);
    
  3. 线条

    long numbyte1 = av[1];
    long numbyte2 = av[2];
    

    遭受同样的问题。您可以使用已提取的数字来初始化numbypte1numbypte2

    long numbyte1 = num1;
    long numbyte2 = num2;
    
  4. 你有

    char buffer[num2];
    

    这不足以容纳具有num2字符的字符串。您需要数组中的另一个元素来保存终止 null 字符。用:

    char buffer[num2+1];
    
  5. 文件中读取数据后,将终止空字符添加到buffer

    if(read(fd, buffer, numbyte2) != numbyte2) return 1;
    buffer[num2] = '';
    

最新更新