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.

  • 1
    Declare the file contents as data in the executable?
    – Max
    Jul 22 '12 at 11:02
  • The file contents can be anything. How will you declare them earlier? Jul 22 '12 at 11:12
  • 2
    I suppose you could mmap() it, but that call is part of POSIX, not C.
    – Blrfl
    Jul 22 '12 at 11:29
  • 4
    @Skkard: That's a good point. This impresses me as one of those "trivial if you've seen it before" problems, and I think I'd probe the interviewer about why he thinks abandoning what's pretty much an essential feature is a good idea.
    – Blrfl
    Jul 22 '12 at 12:19
  • 5
    The correct answer is: "Hey look at the time I have an interview with a company that doesn't ask stupid useless trivia in their interview... I will call you." Jul 23 '12 at 14:18

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.


Not the answer you're looking for? Browse other questions tagged or ask your own question.