Accessing Files in CUniversity of Rhode IslandApril 13, 1999 (Revised May28, 2000)
1. IntroductionAccessing files in C can be painful. We've tried to summarize what you need put in your programs to do basic file manipulations.2. C Tips - File Manipulation:There are several ways to read and write files in C. It can be done indirectly via command line re-direction (don't worry if you don't know what that means), or directly with explicit file control statements in C (fprintf()). Regardless of whether you are reading or writing a file, you must first "open" it, and once done accessing the file, you must "close" it. Examples of these four operations are now given with brief descriptions.As always, for all of the gory detail you should refer to a C manual.
For a quick overview and basic concepts, see: Introduction
to C Programming - Text Files in C
Declarations:#include <stdio.h> /* include I/O library - required */FILE *fp; /* file pointer - required */ #define mlos 90
/* max. characters per input line
Opening a File:/* to Write (overwrite) a file, from the beginning */if ((fp=fopen("filename","w"))==NULL){ /* error */ } /* to Append to the end of a file */
/* to Read a file, from the beginning */
Reading a File:Using string-reading fgets():/* fgets(input_data_pointer [string array],maximum_length_of_string, file_pointer)*/ while (fgets(line,mlos,fp)!=NULL){ /* read 'til the end */ } Using formatted-data-reading fscanf():/* fscanf(file_pointer, format_statements, data) -latter two fields are just like printf() */ /* Reads contiguous non-blank ASCII string interpreted as */ /* hex integer. Data is put into successive locations */ /* of array "datain". Goes to the End-Of-File. */ while (fscanf(fp, "%x", &datain[i++]) != EOF); Writing a File:fprintf(fp,"This text appears in the file, followed by a hex integer: %0x \n",datum);Closing a File:fclose(fp);
|