Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can open files in C?

Status
Not open for further replies.

SurgingShark

Programmer
Jul 4, 2002
1
US
How can I open files in C?
 
Once you've declare a file pointer to the file,you can use the function "fopen"
to open it.

the syntaxe for "fopen" is:
FILE *fopen( const char *filename, const char *mode );

the "mode" parameter can be one of those.

"r"

Opens for reading. If the file does not exist or cannot be found, the fopen call fails.

"w"

Opens an empty file for writing. If the given file exists, its contents are destroyed.

"a"

Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn’t exist.

"r+"

Opens for both reading and writing. (The file must exist.)

"w+"

Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"a+"

Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn’t exist.


An example:

FILE *fp; /*declaration of file pointer*/
fp = fopen("myfile.txt", "r" );
if( !fp )
printf("error while opening the file \"myfile.txt\""); /* checks if the file has been open properly */

this will open a file named "myfile.txt" in reading mode.
once you've finish using the file,you can close it by calling "fclose".

so,in our example it would be: fclose(fp);

 
Instead of writing:

if( !fp )
printf("error while opening the file \"myfile.txt\""); /* checks if the file has been open properly */

You could also use

if (!fp)
perror("myfile.txt");

This will print a descriptive message on the stderr device using the errno value that is set in the call to fopen().

E.g.

myfile.txt: No such file or directory
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top