简体   繁体   English

试图打开文件名可变的文件时,c程序崩溃

[英]c program crashes while trying to open a file with variable filename

As stated in the title, i ask for the user to provide the filename and i use gets to save it in str . 如标题中所述,我要求用户提供文件名,然后使用gets将其保存在str Then i try to access the file using the name and the program crashes. 然后,我尝试使用该名称访问文件,并且程序崩溃。

int openFile(FILE *fp){
    puts("What's the name of the file (and format) to be accessed?");
    char str[64];
    gets(str);  
    fp = fopen((const char *)str, 'r');
    ...
    return 0;

In main: 在主要方面:

FILE *fp; // file pointer

openFile(fp);

The filename i enter (data.txt) is indeed in the same directory as the rest of the project so that should not be the problem. 我输入的文件名(data.txt)确实与项目的其余部分位于同一目录中,所以这不应该是问题。 I've tried testing if the file is opened correctly (which it should) but it keeps crashing right after i give the name. 我试过测试文件是否正确打开(应该打开),但是在输入名称后,它一直崩溃。

The main problem is that you are trying to set an argument passed by value in a function and expect the value to be changed outside. 主要问题是您试图在函数中设置一个由值传递的参数,并期望该值在外部被更改。 This can't work. 这行不通。

Currently you have: 目前您有:

void openFile(FILE* fp) {
  fp = ...
}

int main()
{
  FILE* fp;
  openFile(fp);
}

But fp in main() is passed as a pointer by value. 但是main() fp作为值的指针传递。 Which means that inside openFile you are setting a local variable, while the passed one is not modified. 这意味着在openFile内部,您正在设置一个局部变量,而传递的变量未修改。

To solve the problem you can: 要解决该问题,您可以:

  • directly return a FILE* from openFile 直接从openFile返回FILE*
  • accept a pointer to pointer argument to be able to set it, eg void openFile(FILE** fp) and then openFile(&fp) 接受一个指向该指针参数的指针以进行设置,例如,先void openFile(FILE** fp) ,然后再设置openFile(&fp)

Mind that the second argument of fopen is a const char* not a single char , "r" should be used. 注意fopen的第二个参数是const char*而不是单个char ,应使用"r"

It should be fp = fopen(str, "r"); 应该是fp = fopen(str, "r"); , because fopen() expects mode as a char * pointing to a string, rather than a single char . ,因为fopen()希望mode为指向字符串的char *而不是单个char

Also, since parameters in C are passed by value , your fp won't get modified after openFile() is called. 另外,由于C中的参数是通过value传递的 ,因此调用openFile()后,您的fp将不会被修改。 To get it work, you'll have to rewrite it, and call it by openFile(&fp); 要使其正常工作,您必须重写它,然后通过openFile(&fp);对其进行调用openFile(&fp); . Here is an example: 这是一个例子:

void openFile(FILE **fp) {
    puts("What's the name of the file (and format) to be accessed?");
    char str[64];
    fgets(str, 64, stdin);
    str[strcspn(str, "\n")] = '\0';  
    *fp = fopen(str, "r");
}

fgets() is used to provide buffer overflow protection. fgets()用于提供缓冲区溢出保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM