Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
fread/fwrite
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="John Gordon, post: 5029001"] They are for reading/writing chunks of data to/from a stream. You could use them for that purpose. They can also work with other block sizes. It can be more efficient to work with whole blocks at once, rather than one character at a time. Here's a sample using fread to read up to 1000 characters from a file: char buf[1000]; FILE *fp; fp = fopen("filename.txt", "r"); bytes_read = fread(buf, 1, sizeof(buf) - 1, fp); buf[bytes_read] = 0; fclose(fp); Here's a sample using fwrite to write a fixed message to a file: char *message = "Hello earthlings."; FILE *fp; fp = fopen("message.txt", "w"); bytes_written = fwrite(message, 1, strlen(message), fp); fclose(fp); The first argument to fread/fwrite is a pointer to the buffer being read or written. The second argument is the size of each element being read/written. In these examples we're writing characters, so the size is 1. If we were writing other objects, we would use the size of those objects. The third argument is the number of elements to be read/written. The fourth argument is the stream to which the elements are to be read/written. The return value is the number of elements actually read/written, which may be less than the number you requested, in which case you'll have to keep calling fread/fwrite until all the data gets processed. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
fread/fwrite
Top