C 系统调用 — 使用 lseek 和 read 不断出错

标签 c unix system

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

我在尝试从变量 (num2) 分配长度的 char 数组(缓冲区)时遇到问题。

你可以像这样执行文件:

./file.c offset numOfChars filename.txt

./file.c 4 10 somefile.txt

如果某个文件包含文本:

Why isn't this c program working. I can't figure it out

程序应该打印

isn't this

代码如下:

#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("%s\n", 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: In function ‘main’:
    soc.c:4:15: warning: initialization makes integer from pointer without a cast [enabled by default]
    int num1 = av[1];
               ^
    soc.c:5:15: warning: initialization makes integer from pointer without a cast [enabled by default]
    int num2 = av[2];
    

    av[1] and av[2] are of type char*. If the contain integers, you can extract the integers from them by using one of several functions from the standard library. E.g.

    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 个字符的字符串。您需要数组中的另一个元素来保存终止空字符。使用:

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

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

关于C 系统调用 — 使用 lseek 和 read 不断出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29191122/

相关文章:

c++ - 如何在C++中捕获多个信号?

c - 如何在 C 中创建一个在父进程死亡后运行的进程?

linux - 如何将 cron 作业输出重定向到标准输出

linux - 在 Linux 中列出进程文件的程序

linux - 移动超过一天的文件

perl - CPAN shell 内存不足。如何在 Unix 上给它更多内存?

当 fork() 遇到 fopen() 时的困惑

c - C11 中的输出参数或返回结构?

c - 我将代码从 FreeBSD 移植到 Linux,但它没有提取目标地址

c - 为什么需要为 GCC 中的代码覆盖传递两个编译器标志