【问题标题】:Errors opening a file in c在 c 中打开文件时出错
【发布时间】:2015-02-19 20:35:08
【问题描述】:

目前我在尝试打开文件时遇到以下问题,无论我给它什么,该功能似乎都无法打开文件。我目前正在传递“./input.txt”,它是与可执行文件位于同一目录中的文件。你们看到的代码有什么明显的错误吗?

FILE* openInputFile(char* inputFileName) 
{
    FILE* ifp= NULL;

    printf("%s\n", inputFileName);
    ifp = fopen(inputFileName, "rb");

    if(ifp == NULL)
    {
        printf("Error opening input file.\n");              
    }

    return ifp;
}

【问题讨论】:

  • 你使用的是 windows 还是 unix?
  • 否;可以挑选一些次要的尼特,但我没有看到任何主要的。您的问题可能是您的进程的当前目录不是您认为的目录。当前目录将是启动进程的 shell 的当前目录,而不是在其中找到代码的目录。您可以通过strerror()errno 打印错误以查看发生了什么问题,但它可能只是说“没有这样的文件或目录”。您可以使用getcwd() 打印出工作目录。
  • @ojblass:标签说“Linux”。
  • 代码对我来说看起来不错。将一些带有实际错误代码的 printf 放在那里会很有用。
  • 将错误后的 printf 更改为 perror - 这将解释失败

标签: c linux file-io


【解决方案1】:

我编译了代码。它工作正常。仔细检查文件是否存在于您认为存在的位置。如果存在,请确保文件权限允许运行程序的用户读取文件。

[user@localhost]$ vim test.c
[user@localhost]$ gcc test.c -o test
[user@localhost]$ ./test
./input.txt
Error opening input file: No such file or directory
[user@localhost]$ touch ./input.txt
[user@localhost]$ ./test
./input.txt
[user@localhost]$ cat test.c
#include <stdio.h>
#include <stdlib.h>

FILE* openInputFile(char* inputFileName) 
{
    FILE* ifp= NULL;

    printf("%s\n", inputFileName);
    ifp = fopen(inputFileName, "rb");

    if(ifp == NULL)
    {
        perror("Error opening input file");              
    }

    return ifp;
}

int main(int argc, char * arv[]){
    openInputFile("./input.txt");
}
[user@localhost]$ ls -la ./input.txt
-rw-rw-r--. 1 user user 0 Feb 19 15:37 ./input.txt

【讨论】:

  • 如果程序的其他部分没有内存问题,也要小心。您可以在 gcc 中对变量设置监视。
【解决方案2】:

您正在返回一个指向存储在堆栈上的内存的指针。当函数退出时,内存被释放并且您指向未分配的内存。必须将指针作为参数传入才能返回文件名:

void openInputFile(char* inputFileName, FILE* ifp)
{
    FILE* ifp= NULL;

    printf("%s\n", inputFileName);
    ifp = fopen(inputFileName, "rb");

    if(ifp == NULL)
    {
        printf("Error opening input file.\n");              
    }
}

【讨论】:

  • 我相信你的方法中有一个额外的FILE *ifp 声明。
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
相关资源
最近更新 更多