警告:传递"fopen"的参数2会使指针从整数开始而无需强制转换 [英] warning: passing argument 2 of ‘fopen’ makes pointer from integer without a cast

查看:374
本文介绍了警告:传递"fopen"的参数2会使指针从整数开始而无需强制转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能来检查文件是否存在:

I have this function to check if a file exists:

#include <stdio.h>

int main(int argc, char **argv) {
    int textFileExists(const char *filename){
        FILE *fp=   fopen(filename,'r');
        if(fp==NULL){
            printf("%s %s.\n","There was an error opening ", filename);
            return -1;
        }
        return 1;
    }

    textFileExists("text.txt");
    return 0;
}

但是当我编译这段代码时,我得到了这个警告.

But when I compile this code, I get this warning.

warning: passing argument 2 of ‘fopen’ makes pointer from integer without a cast
  FILE *fp= fopen(filename,'r');

运行此代码会给我带来细分错误.

Running this code gives me a segmentation fault.

这是怎么回事?

推荐答案

将文字'r'用作fopen参数的用法等同于使用以下内容:

The usage of literal 'r' as fopen parameter is equivalent to using the following:

const char* filename = ...;
char mode = 'r';
fopen(filename, mode);

因此,假定'r'的类型为char,其值为0x72(ASCII).然后将其传递给char* mode,将0x72转换为要读取的存储器地址(指针),以通过fopen获得mode字符串的字符.在0x72处访问内存位置失败,因为该位置很可能对您的应用程序不可用.

The 'r' is therefore assumed to be of type char and has the value of 0x72 (ASCII). This is then passed to the char* mode, converting the 0x72 to a memory address (pointer) to be read from to obtain the characters of mode string by fopen. Accessing the memory location at 0x72 fails as that location is most probably not available to your application.

对于char*文字,您需要像

中那样使用"r"

For a char* literal, you need to use "r" as in

const char* filename = ...;
const char* mode = "r";
fopen(filename, mode);

这篇关于警告:传递"fopen"的参数2会使指针从整数开始而无需强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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