Wikipedia

Hasil penelusuran

Sabtu, 21 November 2015

File in C

A File represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.

How to Create a File

        FILE *fileptr // File pointer called fileptr
         fileptr = fopen()

Opening a File

 use the fopen( ) function to create a new file or to open an existing file.

    FILE *fopen( const char * filename, const char * mode );
 
 
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −



r/rb :Opens an existing text file for reading purpose.
w/wb :Opens a text file for writing. If it does not exist, then a new file is created. Here your  program will start writing content from the beginning of the file.
a/ab ;Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
r+/r+b ;Opens a text file for both reading and writing.
w+/w+b ;Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
a+/a+b; Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use the ones with 'b' in the above.




Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −

     int fclose( FILE *fp );
 
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file.

Reading a File

   int fgetc( FILE * fp );
 
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −

   char *fgets( char *buf, int n, FILE *fp );
 
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.

 Example :




 Since line 6 - 9 already create the file., if we delete line 6-9, it will still compile the same result, because the file is already saved

You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character.
example :






more at :
 http://www.tutorialspoint.com/cprogramming /c_file_io.htm









Tidak ada komentar:

Posting Komentar