Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file for reading in C?

Tags:

c

gcc

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

I do not understand the difference between these 2 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 can't be open, right?

The second method that i use is:

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

fd would be -1 if an error occurs at opening the file.

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

like image 764
appoll Avatar asked May 14 '12 21:05

appoll


People also ask

What opens file in C?

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc.


1 Answers

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

Unless you're in need of doing low level I/O, the stdio functions serve the vast majority of applications very well. It's more convenient, and, in the normal cases, just as fast when used correctly.

like image 185
Kevin Hsu Avatar answered Sep 22 '22 01:09

Kevin Hsu