<< Chapter < Page Chapter >> Page >
fp = fopen(filename, "r"); if(fp == NULL){ fprintf(stderr, "can't open file\n");return; }

or

while(fgets(line, max, fp) != NULL) {... process input ... }if(ferror(fp)) fprintf(stderr, "error reading input\n");

or

fprintf(fp, "%d %d %d\n", a, b, c); if(ferror(fp))fprintf(stderr, "output write error\n");

Error messages are much more useful, however, if they include a bit more information, such as the name of the file for which the operation is failing, and if possible why it is failing. For example, here is a more polite way to report that a file could not be opened:

#include<stdio.h>/* for fopen */ #include<errno.h>/* for errno */ #include<string.h>/* for strerror */ fp = fopen(filename, "r");if(fp == NULL) {fprintf(stderr, "can't open %s for reading: %s\n", filename, strerror(errno));return; }

errno is a global variable, declared in<errno.h>, which may contain a numeric code indicating the reason for a recent system-related error such as inability to open a file. The strerror function takes an errno code and returns a human-readable string such as “No such file” or “Permission denied”.

An even more useful error message, especially for a “toolkit” program intended to be used in conjunction with other programs, would include in the message text the name of the program reporting the error.

Access to binary files

Write data to binary files

size_t fwrite(void *buf, size_t sz, size_t n, FILE *fp)

This function writes to file associated with fp, num number of objects, each object size bytes long, from the buffer pointed to by buffer.

Return value: It returns the number of objects written. This value will be less than num only if an output error as occurred.

The void pointer is a pointer that can point to any type of data without the use of a TYPE cast (known as a generic pointer). The type size_t is a variable that is able to hold a value equal to the size of the largest object surported by the compiler.

As a simple example, this program write an integer value to a file called MYFILE using its internal, binary representation.

#include<stdio.h>/* header file */ #include<stdlib.h>void main(void) {FILE *fp; /* file pointer */ int i;/* open file for output */ if ((fp = fopen("myfile", "w"))==NULL){printf("Cannot open file \n"); exit(1);} i=100;if (fwrite(&i, 2, 1, fp) !=1){ printf("Write error occurred");exit(1); }fclose(fp); }

Read data from binary files

size_t fread(void *buf, size_t sz, size_t n, FILE *fp)

fread reads up to n objects, each of size sz, from the file specified by fp, and copies them to the buffer pointed to by buf. It reads them as a stream of bytes, without doing any particular formatting or other interpretation. (However, the default underlying stdio machinery may still translate newline characters unless the stream is open in binary or "b" mode).

Return value: returns the number of items read. It returns 0 (not EOF) at end-of-file.

#include<stdio.h>int main() { FILE *file;char c[30]; /* make sure it is large enough to hold all the data! */char *d; int n;file = fopen("numbers.txt", "r"); if(file==NULL) {printf("Error: can't open file.\n"); return 1;} else {printf("File opened successfully.\n");n = fread(c, 1, 10, file); /* passing a char array, reading 10 characters */c[n] = '\0'; /* a char array is only astring if it has the null character at the end */printf("%s\n", c); /* print out the string */ printf("Characters read: %d\n\n", n);fclose(file); /* to read the file from the beginning, */ /* we need to close and reopen the file */file = fopen("numbers.txt", "r"); n = fread(d, 1, 10, file);/* passing a char pointer this time - 10 is irrelevant */ printf("%s\n", d);printf("Characters read: %d\n\n", n); fclose(file);return 0; }}
Got questions? Get instant answers now!

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?

Ask