C File Handling – How to Read a File Without Using a File Pointer

cfile handlinglinux

I was asked this question in an interview. I'm somehow supposed to "read" a file into my C program as input without using a file pointer (including "f" functions, e.g. fgets, fscanf etc.). I'm also not allowed to redirect it using the terminal, i.e. no system or exec calls. The program will not get the file during runtime.

I'd like to know how it'd be possible to do this.

Best Answer

File pointers are not the only way to access files on POSIX systems (which, obviously Linux is).
As a matter of fact, the FILE struct exists to make it easier to work with files in a cross-platform manner (fopen() will work on both Linux, Mac OS X, any BSD and Windows) and to provide some facilities like transparent buffering (buffered I/O is way faster).
This is all usually good, unless it's counter-productive (you need the file to be synced for common access from many processes) or dangerous (buffered output might not be flushed when necessary and it might leave the file in a bad state if interrupted improperly). Now, I'm not an expert and these issues might be nonexistent, but there certainly are reasons to use the lower-level API provided by POSIX: the file descriptor mechanism, open(), read(), write(), close() and mmap().

These functions are the building blocks of the FILE* abstraction, under Linux, at least (you can test that by running a sample file I/O program with strace) and you can use them if you want direct access to a file.

This is probably the solution to the problem the interviewer was expecting. The reason he might want you to know this is if you were interviewed for a job in embedded systems; knowledge of the underlying system is essential in such a position.

I once met a Linux programming guru, who said to me that he thinks a person may claim he knows C when he can implement the whole standard library by himself on at least one platform without any significant difficulties. In certain domains, low-level knowledge is a must.