在尝试打开带有可变文件名的文件c程序崩溃 [英] c program crashes while trying to open a file with variable filename

查看:99
本文介绍了在尝试打开带有可变文件名的文件c程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我问为用户提供的文件名和我使用获得将其保存在 STR 。然后我尝试使用名称来访问文件和程序崩溃。

As stated in the title, i ask for the user to provide the filename and i use gets to save it in 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;

在主要的:

FILE *fp; // file pointer

openFile(fp);

我输入文件名(data.txt中)确实是在同一目录中的项目,所以不应该是问题的其余部分。如果文件被正确打开我试图测试(应该),但它总是崩溃之后我给的名称。

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. I've tried testing if the file is opened correctly (which it should) but it keeps crashing right after i give the name.

推荐答案

这应该是 FP = FOPEN(STR,R); ,因为 fopen()函数期望模式的char * 指向一个字串,而多单字符

It should be fp = fopen(str, "r");, because fopen() expects mode as a char * pointing to a string, rather than a single char.

此外,由于在C组参数是按值,您 FP 不会得到后修改中openFile传递( )被调用。为了得到它的工作,你就必须重写它,并通过叫它中openFile(安培; FP); 。下面是一个例子:

Also, since parameters in C are passed by value, your fp won't get modified after openFile() is called. To get it work, you'll have to rewrite it, and call it by 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()用于提供缓冲区溢出保护。

fgets() is used to provide buffer overflow protection.

这篇关于在尝试打开带有可变文件名的文件c程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆