Visual Studio提示'too few argument in function call'无法打开文件如何解决
报错原因
fopen_s是微软推出的C标准库安全增强函数,函数原型和传统fopen完全不同,要求传入3个参数,你只传入了2个参数,直接触发too few argument in function call的编译错误。- 你当前的写法把
fopen_s的返回值当成文件指针赋值,本身逻辑也错误,即使编译通过也无法正常打开文件。
解决方案
方案1:正确使用fopen_s
fopen_s的第一个参数需要传入文件指针的地址,返回值为错误码,修改后代码如下:
#include <stdio.h> int main() { FILE* fp; errno_t open_err; open_err = fopen_s(&fp, "testfile.txt", "w"); if (open_err == 0) { // 打开成功,此处可执行文件读写操作 fclose(fp); } else { printf("文件打开失败,错误码:%d", open_err); } return 0; }
方案2:改用标准fopen函数
如果需要代码兼容其他编译器,建议使用C标准库的fopen函数,代码如下:
// 加此行可以屏蔽VS对fopen的不安全警告 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { FILE* fp = fopen("testfile.txt", "w"); if (fp != NULL) { // 打开成功,此处可执行文件读写操作 fclose(fp); } else { perror("文件打开失败"); } return 0; }
内容的提问来源于stack exchange,提问作者user16790547
相关产品推荐
相关产品推荐

