c - 从指定行读取文件到另一行

标签 c

我目前有一个 C 语言的 shell 脚本,它接受一个文件的命令、两个数字、第 m 行和第 n 行,并且应该输出这些行之间的内容:

例如:

./output file1 2 6

将从第 2 行到第 6 行输出文件

我目前以输出整个文件的方式实现它,我一直在尝试将其更改为专门在这些行之间输出

这是我的代码

#include <fcntl.h>

int main(int argc, char *argv[])
{
    int file;
    int size;
    int l[1000];

    int firstNum = atoi(argv[2]);

    int secondNum = atoi(argv[3]);


    file = open(argv[1], O_RDONLY);

    if( file == -1)
    {
        printf("\n cannot open file \n");
    }

    while ((size=read(file,l,80)) > 0)
        write(1,l,size);




}

我尝试将 lsize 更改为 firstNumsecondNum,它们是从命令行,但仍然没有工作并输出一行。

这样做的更好方法是什么?

最佳答案

您的代码有几个问题,因此请按顺序检查它们:

  • 最好使用高级 fopen 而不是低级 open 打开文件。所以最好这样写:

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
        exit(EXIT_FAILURE);
    
  • 您的 read 是错误的,因为它恰好读取了 80 个字符,而不是您预期的一行。

    while ((size=read(file,l,80)) > 0)   // <-- WRONG because this reads 80 chars instead of one line
    
  • 出于与 open 类似的原因,最好使用 printf 之类的替代方法,而不是低级 read

  • 要逐行读取,您应该使用库函数getline

  • 要控制要打印的行号,一个简单的方法是使用一个变量来跟踪行号并与您的命令行参数进行比较。

所以把它们放在一起,你需要这样的东西:

FILE *file = fopen(argv[1], "r");
if (file == NULL)
    exit(EXIT_FAILURE);

int line_num = 0;

char * line = NULL;
size_t len = 0;
ssize_t read = 0;
while ((read = getline(&line, &len, file)) != -1)
{
    line_num++;
    if( firstNum <= line_num && line_num <= secondNum )
    {
        printf( "line %d: %s", line_num, line );
        if( line_num == secondNum )
            break;
    }
}

关于c - 从指定行读取文件到另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192412/

相关文章:

CMakeLists 多个源文件

CGI 无法在 MAMP 下打印

c - Turbo C++ 错误地执行条件为文字 0 的循环

c - 在 Objective-C 中获取静态 C 数组的长度

c - 访问另一个结构中的结构数组

c - malloc 二维数组导致 EXC_BAD_ACCESS

c - fflush(stdin) 不能在 cygwin 中用 gcc 编译,但可以用 visual studio 2010 编译

c++ - 这些(bCondition == NULL)和(NULL==bCondition)有什么区别?

c - 多进程服务器还是多线程服务器?

c - 为什么要重新加载 C 中的静态局部变量?