Jumat, 27 November 2015

File in C

Hello readers!

i want to show you about File in C.

File

  • Place to save the collection of data record.
  • 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.C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.

Opening Files

We use fopen() to create a new file or open a file.

FILE *fopen( const char * filename, const char * mode );

filename: string liberal, used to name our file
mode: 
ModeDescription
rOpens an existing text file for reading purpose.
wOpens a text file for writing. If it does not exist, then a new file is created. 
aOpens a text file for writing in appending mode. If it does not exist, then a new file is created.
r+Opens a text file for both reading and writing.
w+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+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.

Closing Files

We use fclose() function to close a file.

int fclose( FILE *fp );

fclose(-) function returns zero on success, or EOF if there is an error in closing the file.

Writing Files

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error.

Reading Files

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 EOFThe 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 nullcharacter to terminate the string.
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:



That's the Structs in C. Hope this will help you. Thanks! :D

nb: Some source that really helps me very much (recommended):
http://www.tutorialspoint.com/cprogramming/c_file_io.htm




Tidak ada komentar:

Posting Komentar