我正在尝试根据MSDN示例使用fopen_s
读取文件,但我一直收到访问冲突错误(我甚至尝试过使用常规fopen
但是也一样错误。我的函数中的错误指向err
,我不明白为什么这是一个问题:
char* Foo::readFile(const char* filename)
{
FILE* fp = NULL;
errno_t err = fopen_s(&fp, filename, "r"); // error points to this line
fseek(fp, 0, SEEK_END);
long file_length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* contents = new char[file_length + 1];
for (int i = 0; i < file_length + 1; i++)
{
contents[i] = 0;
}
fread(contents, 1, file_length, fp);
contents[file_length + 1] = '\0';
if (fp)
err = fclose(fp);
return contents;
}
修订后的版本也会出现同样的错误:
FILE* fp = fopen(filename, "r"); // error again points to this line
fseek(fp, 0, SEEK_END);
long file_length = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* contents = new char[file_length + 1];
for (int i = 0; i < file_length + 1; i++)
{
contents[i] = 0;
}
fread(contents, 1, file_length, fp);
contents[file_length + 1] = '\0';
fclose(fp);
return contents;
我的文件以text1.txt和text2.txt的形式驻留在源文件中。在调用函数时:
char* fileData1 = readFile("text1.txt");
char* fileData2 = readFile("text2.txt");