【问题标题】:Read the file error C_language读取文件错误 C_language
【发布时间】:2015-04-23 23:29:51
【问题描述】:

我正在尝试创建文件并在其上写入一些数据,但是当我运行以下代码时,程序运行出错:错误 1 ​​错误 C2664: 'errno_t fopen_s(FILE **,const char *,const char *)' : 无法将参数 1 从 'FILE *' 转换为 'FILE **'

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

FILE *myFile;


int main()
{
    int age;
    age = 24;
    fopen_s(myFile,"C:\\inetpub\\wwwroot\\DATA.EMP", "w");
    if (myFile == 0){
        printf("Error opening the file\n");
        exit(1);
    }
    fprintf(myFile, "I am %d years old \n", age);
    fclose(myFile);

    getchar();
    return 0;
}

可能是什么原因?

【问题讨论】:

  • 编译器错误告诉你很清楚。 fopen_s 需要 FILE ** 类型的 arg 1,而您正在给它 FILE *。尝试使用第一个参数&amp;myFile
  • 我知道了,我已经声明为 FILE **myFile;但它给了我另一个错误 Degub Assertion failed!程序:....al studio 2013\projects\file_pointer1\debug\file_pointer1.exe 文件:f:\dd\vctools\crt\stdio\fopen.c 行:159 表达式:(pfile!=NULL) #include #include 文件 **myFile; int main() { int 年龄;年龄 = 24; fopen_s(myFile,"C:\\inetpub\\wwwroot\\DATA.EMP", "w"); if (myFile == 0){ printf("打开文件出错\n");退出(1); } fprintf(*myFile, "我 %d 岁 \n", age); fclose(*我的文件);获取字符();返回0; }
  • 不,不要那样做!如您所见,这将编译但会在运行时失败。 fopen_s 调用将取消对第一个参数的引用。您必须给它一个指向已分配内存的指针。通过使您的变量FILE ** 您将无效指针传递给 fopen_s。执行建议的操作:声明为FILE * 并将&amp;myFile 传递给fopen_s。在继续之前,您可能想复习一下指针。
  • 是时候阅读手册了(正如你应该为每个系统函数调用做的那样)。有人说,魔鬼藏在细节中。

标签: c file fopen


【解决方案1】:

https://msdn.microsoft.com/en-us/library/z5hh6ee9.aspx

errno_t fopen_s( 
   FILE** pFile,
   const char *filename,
   const char *mode 
);

因此,您的代码应该是:

fopen_s(&myFile,"C:\\inetpub\\wwwroot\\DATA.EMP", "w");

注意&myFile.

并检查您的返回值。

【讨论】:

  • 谢谢,我错过了,我应该参考存储数据的变量地址
猜你喜欢
  • 2017-07-09
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多