我在Windows8.1,Visual 2013 Express中编写了一些代码。现在,我试图在我的上传输并运行这个代码,它运行Debian8.1Jessie。这是我第一次使用Linux,所以我遇到了一些问题。
#include <iostream>
#include <errno.h>
#include <stdio.h>
using namespace std;
int main()
{
FILE *cfPtr;
errno_t err;
if ((err = fopen_s(&cfPtr, "objects.txt", "a +")) != 0) // Check if we can reach the file
cout << "The file 'objects.txt' was not opened.\n";
else
fclose(cfPtr);
return 0;
}
我用以下方法编译这段代码:
g++ source.cpp -o源
但它给了我一些..。在此范围内未声明错误。
source.cpp: In function ‘int main()’:
source.cpp:10:4: error: ‘errno_t’ was not declared in this scope
source.cpp:10:12: error: expected ‘;’ before ‘err’
source.cpp:12:8: error: ‘err’ was not declared in this scope
source.cpp:12:50: error: ‘fopen_s’ was not declared in this scope
我明白了,Windows的*_s函数,那么我如何解决这个问题和errno_t问题呢?
谢谢。
发布于 2015-11-02 23:30:35
正如您所说的,fopen_s是C标准库的Microsoft特定扩展,您需要使用fopen。
现在,errno_t基本上只是一个int,所以您可以使用一个int。
我建议这样做:
#include <iostream>
#include <stdio.h>
using namespace std; // bad
int main(){
FILE *cfPtr = fopen("objects.txt", "r");
if (cfPtr == NULL){
cout << "The file 'objects.txt' was not opened.\n";
} else {
cout << "Success!";
fclose(cfPtr);
}
return 0;
}
请注意,如果"a+“不存在,它将创建一个新文件,因此它在大多数情况下都会正常工作,不管如何。我决定使用"r“代替,因为如果文件不存在,这将失败--作为一个例子。
https://stackoverflow.com/questions/33488793
复制相似问题