Does't work fopen_s(&file, "filename", mode) in visual studio 2019 C_language

Viewed 307

So this is my first question here. If you could help me, that would be much appreciated. This code is about my thesis. I'm trying to write to a file and it works but trying to read another file is not reading. I can't make it work. "file does not open" appears on the screen. Help me please, for read to file.

#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main()
{
    FILE* myfile;
    errno_t errorcode = fopen_s(&myfile, "output.txt", "w");

    if (myfile == NULL)
    {
       printf("Error");
    }

    FILE* data; 
    errno_t err = fopen_s(&data, "C:\SA\input.txt", "r");

    //errno_t err = fopen_s(&data, "input.txt", "r");

    if(data==NULL)
    {
       printf("file does not open");
    }
return 0;
getchar();
}
1 Answers

The original code posted had 2 major issues:

  • "C:\SA\input.txt" should be "C:\\SA\\input.txt" or simply "C:/SA/input.txt". Microsoft's legacy systems use \ as a path separator which must be escaped in C strings as \\ (and in many other languages too). The traditional path separator on POSIX systems is / and it is also supported in Windows.
  • if(data==NULL); is a test with an empty statement, hence nothing happens.
  • Note that you should not use C++ headers such as <iostream> in a C program.

Here is a simplified version:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    FILE *myfile;
    errno_t err = fopen_s(&myfile, "output.txt", "w");
    if (err) {
        fprintf(stderr, "Cannot open file %s: %s\n",
                "output.txt", strerror(err));
        return 1;
    }

    FILE *data; 
    err = fopen_s(&data, "C:\\SA\\input.txt", "r");
    if (err) {
        fprintf(stderr, "Cannot open file %s: %s\n",
                "C:\\SA\\input.txt.txt", strerror(err));
        return 1;
    }
    getchar();  // keep terminal window open
    return 0;
}
Related