Fopen does not work in linux for a file with German characters in the name

I wrote code in c to process files. There are several German characters in the file name. This code works fine on Windows. But it does not work on Linux. fopen gives the error "Could not open file." I checked the file path, the file exists. In addition, I have write permissions for this folder.

The code is as follows.

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const char *fileName = "/users/common/haëlMünchen.txt"; FILE * pFile; char errorMessage[256]; pFile = fopen (fileName,"r"); if (pFile != NULL) { fprintf (stdout,"fopen example",errorMessage); fclose (pFile); } else { sprintf(errorMessage, "Could not open file %s", fileName); fprintf(stdout, "%s\n", errorMessage); } return 1; } 

Any inputs on this?

+4
source share
1 answer

On Linux, you can replace your sprintf call with

 snprintf (errorMessage, sizeof(errorMessage), "Could not open file %s - %m", fileName); 

(General hint to avoid sprintf due to possible buffer overflows and use only snprintf )

If you want to avoid the %m GLibc format specifier, as well as use more standard functions, the code

 snprintf (errorMessage, sizeof(errorMessage), "Could not open file %s - %s", fileName, strerror(errno)); 

and don't forget the #include <errno.h> , and read the errno (3) man page carefully.

By the way, you could avoid executing both snprintf , printf and just code

 fprintf (stderr, "Cannot open file %s - %s\n", fileName, strerror(errno)); 

(error messages are usually sent to stderr , as Jonathan recalled)

Then run your program again. Perhaps you have a problem with character encoding (either in the source file or in the file system).

You can also use strace (and possibly ltrace ) in your program to understand the actual system calls it makes.

+4
source

Source: https://habr.com/ru/post/1440748/


All Articles