【问题标题】:How to read from a file when passing path as an argument using realpath()使用 realpath() 将路径作为参数传递时如何从文件中读取
【发布时间】:2022-08-18 02:48:59
【问题描述】:

我想使用realpath()(例如:/var/log/message)传递特定文件位置的参数,并使用fprintf 在终端上打印此文件的内容。 这是我到目前为止的代码:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        printf(\"Usage: %s <path>\\n\", argv[0]);
        return 1;
    }
    char *fullpath = realpath(argv[1], NULL);
    FILE *fptr;
    fptr = fopen(fullpath, \"r\");
    fprintf(fptr, \"%s\");
    return 0;
}

它不会抛出错误,但它也不会做我想让它做的事情。 当我运行它时,例如./test /var/log/message 它会在终端上显示这个:

Segmentation fault (core dumped)

操作系统版本

NAME=\"Fedora Linux\"
VERSION=\"36

编译器

gcc
  • 使用fprintf(fptr, \"%s\");,您尝试编写文件,而不是从中读取。互联网上应该有很多关于如何阅读文件的教程,更不用说任何像样的教科书都应该有关于它的章节。
  • 至于问题,您是否检查过您实际调用的函数返回? realpathfopen 都可能失败,你需要检查一下。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如它目前所写的那样,很难准确地说出你在问什么。
  • fprintf(fptr, \"%s\"); 不仅会写入,而且它是未定义的行为(可以但不必出现段错误),因为您没有 %s 格式的字符串参数。
  • 您通常不需要使用realpath() 来打开命令行中指定的文件。只需将argv[1] 传递给fopen()。如果您不打算遍历所有命令行参数,则应检查if (argc != 2)。您应该报告标准错误而不是标准输出的错误。

标签: c realpath


【解决方案1】:

回到我的函数并添加了更多功能,现在它正在通过为其添加参数来工作。 我要做的是声明 fptr 是 FILE 而 c 是字符类型,在文件上运行一个 while 循环并打印其内容,并使用fgetc 将该内容流式传输到终端。

当前代码:

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fptr;
    char c;
    if (argc < 2) {
        printf("You need to grant an arg to %s <path>\n", argv[0]);
        return 1;
    }
    char *fullpath = realpath(argv[1], NULL);
    fptr = fopen(fullpath, "r");
    if (fptr == NULL)
    {
        printf("Cannot open file \n");
        free(fptr);
        exit(0);
    }
    c = fgetc(fptr);
    while (c != EOF)
    {
        printf ("%c", c);
        c = fgetc(fptr);
    }
    fclose(fptr);
    return 0;
}

谢谢大家的帮助。

【讨论】:

  • 你仍然有内存泄漏。如果您将NULL 传递给realpath 作为第二个参数,它会为返回值执行malloc()。所以,你必须释放它,一旦你完成它。
  • 像这样?说得通
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2014-05-15
  • 2011-04-20
  • 2013-01-25
  • 2020-07-27
  • 2020-02-21
  • 1970-01-01
相关资源
最近更新 更多