Sunday, November 7, 2010

41. Files in C

The library stdio.h defines a structure called FILE.
You don’t need to know any of the details of how a FILE works, you just need to know how to point to them.
A pointer to a file is called a “file handle”.

Writing to a File

void main()
 {
FILE *fp; /* pointer to a file */
/* open WRITEME.txt for reading */
fp = fopen("WRITEME.txt", “w");
/* do stuff with the file */
fprintf(fp,"This goes in the file");
/* close the file -- it’s a good habit */
fclose(fp);
}

fopen

The function fopen accepts a string corresponding to the name of the filename, and another string the says whether we want to open the file to
read ("r"),
Write ("w"), or
append ("a").
If there is any error, fopen returns the pointer value NULL.

Input and Output in File

Up to now, we’ve been using printf to print messages (to “standard output”), and scanf to receive input from the keyboard (from “standard input”).
These can be generalized to the functions fprintf and fscanf, which write to and read from a particular file.

Given a file pointer fp, the statement:
fprintf(fp,"This goes in the file");
writes to the file handled by fp.
The statement: fscanf(fp,"%d",&intvar); reads an integer from the file.

Read and Writing Way

There are more rudimentary ways to read from files and write to files.
Suppose that fp is a file pointer.

The function getc(fp) returns a single character read from the file.
putc(c,fp);
writes the character c to the file.

Finishing of File

feof() returns non-zero if fp reaches end-of-file, otherwise zero.

FILE *fp;
while(!feof(fp))
ch = getc(ch);

Post by J.siam
Ref Herbert Schildt

3 comments:

  1. Thank you very Much. this is understanding very easily and very useful

    ReplyDelete
  2. hi!This was a really wonderful topic!

    ReplyDelete