Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I/O methods in C

Tags:

performance

c

I am looking for various ways of reading/writing data from stdin/stdout. Currently I know about scanf/printf, getchar/putchar and gets/puts. Are there any other ways of doing this? Also I am interesting in knowing that which one is most efficient in terms of Memory and Space.

Thanks in Advance

like image 736
Ravi Gupta Avatar asked Jul 07 '10 11:07

Ravi Gupta


2 Answers

fgets() 
fputs()
read()
write()

And others, details can be found here: http://www.cplusplus.com/reference/clibrary/cstdio/

As per your time question take a look at this: http://en.wikipedia.org/wiki/I/O_bound

like image 184
Bella Avatar answered Sep 23 '22 02:09

Bella


Stdio is designed to be fairly efficient no matter which way you prefer to read data. If you need to do character-by-character reads and writes, they usually expand to macros which just access the buffer except when it's full/empty. For line-by-line text io, use puts/fputs and fgets. (But NEVER use gets because there's no way to control how many bytes it will read!) The printf family (e.g. fprintf) is of course extremely useful for text because it allows you to skip constructing a temporary buffer in memory before writing (and thus lets you avoid thinking about all the memory allocation, overflow, etc. issues). fscanf tends to be much less useful, but mostly because it's difficult to use. If you study the documentation for fscanf well and learn how to use %[, %n, and the numeric specifiers, it can be very powerful!

For large blocks of text (e.g. loading a whole file into memory) or binary data, you can also use the fread and fwrite functions. You should always pass 1 for the size argument and the number of bytes to read/write for the count argument; otherwise it's impossible to tell from the return value how much was successfully read or written.

If you're on a reasonably POSIX-like system (pretty much anything) you can also use the lower-level io functions open, read, write, etc. These are NOT part of the C standard but part of POSIX, and non-POSIX systems usually provide the same functions but possibly with slightly-different behavior (for example, file descriptors may not be numbered sequentially 0,1,2,... like POSIX would require).

like image 45
R.. GitHub STOP HELPING ICE Avatar answered Sep 23 '22 02:09

R.. GitHub STOP HELPING ICE