How to open a file for reading in C?

There is this thing that gives me headaches in C programming when I read from files.

I do not understand the difference between these two methods:

FILE *fd; fd=fopen(name,"r"); // "r" for reading from file, "w" for writing to file //"a" to edit the file 

fd returns NULL if the file cannot be opened, right?

The second method I use:

 int fd; fd=open(name,O_RDONLY); 

fd will be -1 if an error occurs when opening the file.

Would anyone be kind enough to explain this to me? Thanks in advance:)

+6
source share
1 answer

Using fopen () allows you to use the C stdio library, which can be much more convenient than working with file descriptors. For example, there is no built-in equivalent to fprintf (...) with file descriptors.

If you don't need low-level I / O, the stdio functions very well for the vast majority of applications. This is more convenient and, in normal cases, just as fast when used properly.

+10
source

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


All Articles