【问题标题】:Passing filename as argument causing segmentaion fault when the file is not found未找到文件时将文件名作为参数传递导致分段错误
【发布时间】:2021-11-24 03:00:45
【问题描述】:

我想通过将文件名作为命令行参数然后将其传递给函数来打开文件。

打开文件时代码运行良好,但找不到文件时会抛出分段错误错误消息。当我将文件打开逻辑从 runFile 函数转移到 main 函数时,它也可以工作,但是当文件名作为参数传递给函数时会导致分段错误。

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

void runFile(char* fileName);

int main(int argc, char** argv)
{   
    if (argc != 2)
    {   
        printf("Usage: ./lexer [source]\n");
        exit(64);
    }
    else
    {   
        runFile(argv[1]);
    }
    return 0;
}

void runFile(char* file)
{
    FILE *fp;
    if (!filename)
    {
        printf("Error");
    }

    fp = fopen(file, "r");
    if ((fp = fopen(file, "r")) == NULL)
    {
        printf("File not opened!");
    }
    else
    {
        printf("File opened Successfully!\n");
    }



    fclose(fp);
}

【问题讨论】:

  • @user786 呵呵!我不想打开它。我只想在文件不存在时显示错误消息“文件未打开/找到”。
  • if (!filename) ...
  • @wildplasser 这是我复制代码的注释掉部分时出现的错字。问题已经得到解答。

标签: c file


【解决方案1】:

像这样编写runFile() 函数:

void runFile(char* file) {
  FILE* fp = fopen(file, "r");

  if (fp == NULL) {
    printf("File not opened!\n");
    return;
  }

  // do something with the file
  printf("File opened!\n");

  fclose(fp);
}

您的代码的问题是即使fpNULL,您仍然调用fclose(fp)(因为它无法打开文件); fclose(fp) 应该只被调用一次,并且只在 fp != NULL 时调用。

【讨论】:

  • 我实际上想在 printf("File not opened") line where you put the return` 语句之后放置一个 exit(int) 函数。感谢您指出问题。我也不知道 fclose() 应该只在打开文件时调用。现在看来真的很明显。比你!
猜你喜欢
  • 2011-07-06
  • 2021-04-07
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
相关资源
最近更新 更多