Debian 8.1 Jessie中的g ++ errno_t和fopen_s错误

时间:2015-11-02 23:18:04

标签: c++ linux g++ fopen errno

我在Windows 8.1,Visual Studio 2013 Express中编写了一些代码。现在,我正在尝试在运行Debian 8.1 Jessie的Beagle Bone Black上传输并运行此代码。这是我第一次使用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

但是它给了我一些......在这个范围内没有宣布这种错误。

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问题呢?

谢谢。

1 个答案:

答案 0 :(得分:0)

就像你说的,fopen_s是C标准库的Microsoft Windows特定扩展,你需要使用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;
}

请注意&#34; a +&#34;如果它不存在,将创建一个新文件,因此无论如何它都适用于大多数情况。我决定使用&#34; r&#34;相反,如果文件不存在,这将失败 - 作为一个例子。