<< 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!

Questions & Answers

what is phylogeny
Odigie Reply
evolutionary history and relationship of an organism or group of organisms
AI-Robot
ok
Deng
what is biology
Hajah Reply
the study of living organisms and their interactions with one another and their environments
AI-Robot
what is biology
Victoria Reply
HOW CAN MAN ORGAN FUNCTION
Alfred Reply
the diagram of the digestive system
Assiatu Reply
allimentary cannel
Ogenrwot
How does twins formed
William Reply
They formed in two ways first when one sperm and one egg are splited by mitosis or two sperm and two eggs join together
Oluwatobi
what is genetics
Josephine Reply
Genetics is the study of heredity
Misack
how does twins formed?
Misack
What is manual
Hassan Reply
discuss biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles
Joseph Reply
what is biology
Yousuf Reply
the study of living organisms and their interactions with one another and their environment.
Wine
discuss the biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles in an essay form
Joseph Reply
what is the blood cells
Shaker Reply
list any five characteristics of the blood cells
Shaker
lack electricity and its more savely than electronic microscope because its naturally by using of light
Abdullahi Reply
advantage of electronic microscope is easily and clearly while disadvantage is dangerous because its electronic. advantage of light microscope is savely and naturally by sun while disadvantage is not easily,means its not sharp and not clear
Abdullahi
cell theory state that every organisms composed of one or more cell,cell is the basic unit of life
Abdullahi
is like gone fail us
DENG
cells is the basic structure and functions of all living things
Ramadan
What is classification
ISCONT Reply
is organisms that are similar into groups called tara
Yamosa
in what situation (s) would be the use of a scanning electron microscope be ideal and why?
Kenna Reply
A scanning electron microscope (SEM) is ideal for situations requiring high-resolution imaging of surfaces. It is commonly used in materials science, biology, and geology to examine the topography and composition of samples at a nanoscale level. SEM is particularly useful for studying fine details,
Hilary
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

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