1

I have written some code in Windows 8.1, Visual Studio 2013 Express. Now, I am trying to transfer and run this code on my Beagle Bone Black which is running Debian 8.1 Jessie. This is my first time using Linux so I am having some problems.

#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;
}

I compile this code with:

g++ source.cpp -o source

But it gives me some ... was not declared in this scope kind of errors.

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

I see, *_s functions for Windows, so how can I fix this and errno_t problems?

Thank you.

muusssttafa
  • 13
  • 1
  • 4

1 Answers1

0

Like you say, fopen_s is a Microsoft Windows specific extension to the C standard library and you need to use fopen instead.

Now, errno_t is basically just an int, so you could use an int instead.

I'd recommend doing it this way:

#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;
}

Do note that "a+" will create a new file if it doesn't exist, as such it will work in most cases, regardless. I have decided to use "r" instead as this will fail if the file does not exist -- as an example.

Community
  • 1
  • 1
ZN13
  • 1,048
  • 1
  • 11
  • 21