GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
 
 
Thread Tools Search this Thread Rating: Thread Rating: 2 votes, 5.00 average.
  #1  
Old 26-Feb-2004, 01:32
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough

[Tutorial] Standard I/O


Name/Brief Description:
A fairly thorough tutorial of Standard I/O

Date of Original Sumbission:
February, 25th 2004
Modified: March 3, 2004

Submitted by:
Aaron Cohn

License:
For personal use only.

Standard I/O is the most common way of performing I/O in C programs. It has a wider range of commands and in many respects is easier to use than System I/O. Standard I/O conceals from the user some of the details of file I/O operations, such as buffering, and it automatically performs data conversion.

Standard I/O is used mostly to produce reports and read and write data in text format. Standard I/O seems best suited when data is to be stored in text format but can also be used to store data in binary format.

This is a list of the file tasks and related functions we will discuss.

  • fopen() -- Opens a file.
  • fclose() -- Closes a file.
  • fseek() -- Moves file pointer to specified position in a file.
  • ftell() -- Returns the current file pointer position in a file.
  • getc() & fgetc() -- Reads a character from a file.
  • putc() & fputc() -- Writes a character to a file.
  • fgets() -- Reads a string from a file.
  • fputs() -- Writes a string to a file.
  • fscanf() -- Reads a formatted string from a file.
  • fprintf() -- Writes a formatted string to a file.
  • fread() -- Reads a structure from a file.
  • fwrite() -- Writes a structure to a file.
  • fflush() -- Clears stream output buffer.
  • ferror() -- Determines if file operation has produced an error.
  • feof() -- Returns true if end-of-file reached.
  • rewind() -- Resets the file position indicator to the beginning of the file.
  • remove() -- Erases a file.


We discuss each of these functions in detail. The prototype of each function is given followed by discussion of the function in detail including argument definitions. At the end of each function are examples to demonstrate appropriate usage. Each of these functions requires the stdio.h header.
Last edited by dsmith : 03-Mar-2004 at 08:09.
  #2  
Old 27-Feb-2004, 14:10
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
FILE *fopen ( const char *filename, const char *mode);

fopen() opens a file named by filename and associates a stream with it. fopen() returns a pointer to be used to identify the stream in subsequent operations.

Before you can read or write a file, you must open it. Opening a file establishes a link between your program and the operating system. In standard I/O a file pointer must first be created using FILE * in the variable declaration secion. This sets up a structure with the buffer and other items necessary to read and write a file.

For example, to create a variable of type FILE *:
CPP / C++ / C Code:
FILE *fptr;     // note that FILE is in caps and don't
                // forget that asterisk
Parameter: const char *filename

The first parameter is filename. It is a string that contains the name and path of the file. The path should include the drive, the subdirectory, and the full name of the file. If the drive or directory is not valid the function returns NULL to indicate failure.

Examples:
CPP / C++ / C Code:
char *filename = "c:\\data\\students.lst";
if ((fptr = fopen(filename,"rt")) == NULL)
     . . .
if ((fptr = fopen("d:\\names.txt","wt+")) == NULL)
     . . .
Notice that the path uses double slashes for each subdirectory separator. If you use single slashes it could cause problems (this is caused by C). Suppose you used "c:\names\rents.lst". The C compiler interprets \n as the newline character and \r as the carriage return character. You may use upper or lower case for the filenames but beware that some operating systems are case sensitive (like UNIX). Be sure to use the same case for all uses.

Parameter: const char *mode

The mode parameter indicates the read/write mode the file will be opened under. The mod parameter must be one of the following:
  • "r" -- Open the file in text mode for reading. The file must already exist.
  • "w" -- Open the file in text mode for writing. If the file exists, its contents will be overwritten. If it doesn't exist, it will be created.
  • "a" -- Open the file in text mode for appending. Material will be added to the end of an existing file, or a new file will be created.
  • "rb" -- Open the file in binary mode for reading. The file must already exist.
  • "wb" -- Open the file in binary mode for writing. If the file exists, its contents will be overwritten. If it doesn't exist, it will be created.
  • "ab" -- Open the file in binary mode for appending. Material will be added to the end of an existing file, or a new file will be created.
  • "r+" -- Open the file in text mode for both reading and writing. The file must already exist.
  • "w+" -- Open the file in text mode for both reading and writing. If the file exists, then it's contents are overwritten.
  • "a+" -- Open the file in text mode for both reading and appending. If the file doesn't exist, it will be created.
  • "r+b" or "rb+" -- Open the file in binary mode for both reading and writing. The file must already exist.
  • "w+b" or "wb+" -- Open the file in binary mode for both reading and writing. If the file exists, its contents are overwritten.
  • "a+b" or "ab+" -- Open the file in binary mode for both reading and appending. If the file doesn't exist, it will be created.
  • "r+t" or "rt+" -- Open the file in text mode for both reading and writing. The file must already exist.
  • "w+t" or "wt+" -- Open the file in text mode for both reading and writing. If the file exists, its contents are overwritten.
  • "a+t" or "at+" -- Open the file in text mode for both reading and appending. If the file doesn't exist, it will be created.

Notice in the above examples that if you leave off the 't' in the mode parameter the file mode is text by default. However, it is good programming style to always provide the file type when opening a file.

Return Value: FILE *

If the function opens the file successfully, a value of type FILE * is returned. This value must be assigned to a FILE * variable.

If fopen() cannot open the file for any reason it returns NULL.

You must always test for NULL being returned form fopen(). It makes your programs ROBUST. A program that fails to test ALL I/O operations is doomed to fail. For example, suppose you try to open a file on Drive M: (and you don't have a drive M, fopen() would fail. If you don't test for the failure and just proceed, all reads and writes would also fail. This would not be a very logical path to follow!

fopen() example #1:
CPP / C++ / C Code:
FILE *fptr;
fptr = fopen("a:\\data\\customer.dat","w+");
if (fptr == NULL)
  {
    perror("Can't open customer.dat.   Reason");
    exit(0);
  }

line 1: This is the file variable that must be created.
line 2: This opens the file at the path indicated.
line 3: This checks to make sure that the file open correctly.
line 4: This function prints an error message to stderr (usually the monitor)
line 5: This causes the program to terminate and return 0 to the operating system. Do not use this function if you are using C++. exit()(stdlib.h) is an absolute abort which will cause NO destructors to be called.

fopen() example #2:
CPP / C++ / C Code:
FILE *output;
if ((output = fopen(stdprn,"wt")) == NULL)
  {
    printf("printer not available");
    return 0;
  }
line 1: This is the file variable that must be created.
line 2: This opens the file and associates the path as the printer. It also checks to make sure that the file opened correctly.
line 3: This function prints an error message to the monitor.

fopen() example #3:
CPP / C++ / C Code:
FILE *input;
input = fopen("a:\\data\\customer.dat","r+b");
if (input == NULL)
  {
    MessageBox(NULL,"File Open Error",NULL,0);
    return 0;
  }
line 1: This is the file variable that must be created.
line 2: This opens the file for reading or writing at the path indicated.
line 3: This checks to make sure that the file opened correctly.
line 4: This API function prints an error message in a standard error box. This would be used in a windows application.
line 5: This causes the program to return 0 to the calling function to indicate that the file transaction failed.
Last edited by dsmith : 03-Mar-2004 at 08:10.
  #3  
Old 27-Feb-2004, 18:04
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int fclose(FILE* fptr);

Use this function to close any file opened with the fopen() command. This function returns 0 on success and EOF (-1) if any errors were detected. You MUST do this before your program ends. Unpredictable results happen when you don't: Data Loss, Fat Table Problems, Lost Clusters, Crosslinked Files, etc.

Example:
CPP / C++ / C Code:
fclose(fptr);
  #4  
Old 27-Feb-2004, 18:07
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int feof(FILE* fptr);

feof() tests the given stream for an end-of-file indicator. Once the indicator is set, read operations on the file return the indicator until rewind() is called or the file is closed. The end-of-file indicator is reset with each input operation. feof() returns nonzero if an end-of-file indicator was detected on the last input operation on the named stream and 0 if end-of-file has not been reached.

Note: DO NOT USE THIS FUNCTION TO TEST FOR EOF IN A LOOP
The reason for this is that feof() does not test the actual stream, it only tests the indicator. After you read the last character, the EOF indicator is still false (because the read woked fine). So you end up going back through the loop where the read will finally fail and the EOF indicator will become true, but then you end up processing the last thing you read a second time, which is not good at all. It's better to actually use the return value of the function you used to read the data to test if you have reached EOF or not.

CPP / C++ / C Code:
while ((ch = fgetc(fptr)) != EOF)
{
  putc(ch, stdout);
}
Last edited by dsmith : 03-Mar-2004 at 09:25.
  #5  
Old 27-Feb-2004, 18:10
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int fflush(FILE* fptr);

fflush() flushes an output stream. If the given stream has buffered output, fflush() writes the output for stream to the associated file. The stream remains open after fflush() has executed. fflush() has no effect on an unbuffered stream.

fflush() returns 0 on success. It returns EOF if any errors were detected.

"fflush() is not defined in the C/C++ standard for input streams. Therefore is is not guaranteed to work. Although some compilers have define fflush() for input streams, it's use is rare and therefore should be avoided." -WaltP
Last edited by dsmith : 03-Mar-2004 at 08:11.
  #6  
Old 27-Feb-2004, 18:30
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int getc(FILE* fptr);
int fgetc(FILE* fptr);

fgetc() and getc() return the next character on the given input stream and increment the stream's file pointer to point to the next character.

On success, they return the character read after converting it to an int without sign extension. On end-of-file or error, it returns EOF.

Note: For Win32 GUI applications, stdin must be redirected.

Example:
CPP / C++ / C Code:
if ((ch = getc(fptr)) == EOF)
  . . .
  #7  
Old 27-Feb-2004, 18:43
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int putc(int c, FILE* fptr);
int fputc(int c, FILE* fptr);

putc() and fputc() output the character c to the stream given by fptr.

On success, they return the character written to the file. On error, they return EOF.

Example:
CPP / C++ / C Code:
if ((ch = getc(fptr)) == EOF)
  . . .
  #8  
Old 27-Feb-2004, 19:07
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
char* fgets(char* s, int n, FILE* fptr);

fgets() reads characters form a stream into the string s. The function stops reading when it reads either n-1 characters or a newline character, whichever comes first. fgets() retains the newline character at the end of s. A null byte is appended to s to mark the end of the string. On success, it returns the string pointed to by s; it returns NULL on end-of-file or error.

Example:
CPP / C++ / C Code:
if (fgets(str,size,fptr)==NULL)
  . . .
  #9  
Old 27-Feb-2004, 19:13
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int fputs(const char* s, FILE* fptr);

fputs() copies the null-terminated string s to the given output stream. It does not append a newline character, and the terminating null character is not copied. On success, it returns a nonnegative value. On failure, it returns EOF.

Example:
CPP / C++ / C Code:
if (fputs(name,fptr) == EOF)
  . . .

if (fputs("aaroncohn",fptr) > -1)
  . . .
  #10  
Old 27-Feb-2004, 19:18
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 570
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough
int fscanf(FILE* fptr, const char* format, &arg1,...);

This function is identical to scanf() except that it reads from the stream instead of the keyboard. It returns the number of input fields successfully scanned, converted and stored; the return value does not include scanned fields that were not stored. If fscanf() attempts to read at end-of-file, the return value is EOF. If no fields were stored, the return value is 0.

Example:
CPP / C++ / C Code:
count = fscanf(fptr,"Name: %s, Grade: %d",name,grade);
if (count == EOF)
  . . .
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Formatting C / C++ code WaltP C Programming Language 1 07-Jan-2008 00:59
Re: Naming Conventions WaltP C Programming Language 8 06-Jun-2004 22:22
New wi-fi standard approved - here comes 24-54Mbps jrobbio Open Discussion Forum 1 17-Jul-2003 00:29
[Tutorial] XSL Basics Pt. I pcxgamer Web Design Forum 15 22-Apr-2003 06:59

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 09:21.


vBulletin, Copyright © 2000 - 2017, Jelsoft Enterprises Ltd.