|< C & C++ Pointers 3 | Main | C File I/O 2 >| Site Index | Download |


 

 

 

 

MODULE 9 - THE C FILE INPUT/OUTPUT 1

------------------------------------------------------------------------------

MODULE 19: C++ FILE I/O

create this, delete that, write this, read that, close this, open that

 

 

 

 

 

My Training Period: xx   hours

 

The C file input/output skills for this session:

 

The standard C++ file input/output is discussed in C++ file input/output. For C++ and MFC (Windows GUI programming) it is called Serialization and the topics are in Single Document Interface (SDI) and Multiple Document Interface (MDI). The source code for this Module is: C file input/output program source codes. In this Module, trainee must be able to understand and use:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

9.1    Introduction

  • This Module actually shows you how to use the functions readily available in the C standard library.  Always remember this, using the standard library (ISO/IEC C, Single Unix specification or glibc); you must know which functions to call and which header files provide these functions.  Then, you must be familiar with the proper prototype of the function call.

  • The problems normally exist when dealing with the parameters passed to the functions and the return value of the functions.  We will explore some of the very nice and one of the heavily used functions that available in the stdio.h header file, for our file processing and management tasks.

  • Keep in mind that in C++ we will use member functions in class objects for file processing and some of the advanced file processing examples will be discussed in C++ file I/O Module.

  • Storage of data file as you have learned is temporary, all such data is lost when a program terminates.  That is why we have to save files on primary or secondary storage such as disks for future usage.

  • Besides that we also need to process data from external files that may be, located in secondary storage as well as writing file during software installation and communicating with computer devices such as floppy, hard disk, networking etc.

  • And in socket programming (networking) you will also deal a lot with these open, close, read write activities.

  • File used for permanent retention of large amounts of data, stored online or offline in secondary storage devices such as hard disk, CD-Rs/DVDs, tape backup or Network Attached Storage (NAS).

9.2    Basic of The Data Hierarchy

  • Ultimately, all data items processed by a computer are just combinations of zeroes and ones.

  • The smallest data item in computer can assume the value 0 or 1, called a bit (binary digit).

  • But, human being prefer to work with data in the form of decimal digits (i.e. 0, 1, 2, 3, 4, 5, 6, 7…9), letters (i.e. A – Z and a – z) and special symbols (i.e. $, @, %, &, *, (,), -, +, ? and many others) or in readable format.

  • As you know, digits, letters and special symbols are referred to as characters, the keys on your keyboard based on whether the ASCII, EBCDIC, Unicode or other proprietary characters set.

  • Every character in a computer’s character set is represented as a pattern of 1’s and 0’s, called byte (consists 8 bits-ASCII, EBCDIC), and for Unicode it uses multi-byte or wide characters.

  • Characters are composed of bits, and then fields (columns) are composed of characters.

  • A field is a group of characters that conveys meaning such as a field representing a month of year.

  • Data items processed by computer form a data hierarchy in which data items become larger and more complex in structure as we progress from bits, to char (byte) to field and so on.

  • A record (row or tuple) is composed of several fields.

  • For example, in a payroll system, a record for a particular employee might consist of the following fields:

  1. Name.

  2. Address.

  3. Security Social Number (SSN)/Passport Number

  4. Salary.

  5. Year to date earnings.

  6. Overtime claims.

C file I/O data hierarchy

 Figure 9.1:  An illustration of a simple data hierarchy.

9.3    Files And Streams

9.4  Directories, Files and streams

 

9.4.1  Directories (Folders)

C:\Program Files\Microsoft Visual Studio\VC98\Bin

/testo1/testo2/testo3

C file I/O file and directory

9.4.2 File Name Resolution

/Firstdir/Secondir/Thirdir

C:\Firstdir>dir /a

 Volume in drive C has no label.

 Volume Serial Number is E8E3-18E2

 

 Directory of C:\Firstdir

 

04/18/2005  03:09p      <DIR>          .

04/18/2005  03:09p      <DIR>          ..

04/18/2005  03:08p                   0 first.txt

04/18/2005  03:09p      <DIR>          Secondir

               1 File(s)              0 bytes

               3 Dir(s)   1,326,395,392 bytes free

./testrun

File name

Description

/a

The file named a, in the root directory.

/a/b

The file named b, in the directory named a in the root directory.

a

The file named a, in the current working directory.

/a/./b

This is the same as /a/b.

./a

The file named a, in the current working directory.

../a

The file named a, in the parent directory of the current working directory.

 

Table 9.1: File names examples

./testprog

 

9.4.3  Streams and FILE structure

FILE data type

This is the data type used to represent stream objects. A FILE object holds all of the internal state information about the connection to the associated file, including such things as the file position indicator and buffering information. Each stream also has error and end-of-file status indicators that can be tested with the ferror() and feof() functions.

 

Table 9.2: FILE data type

9.4.4  Standard Streams

Standard stream

Description

FILE * stdin

The standard input stream variable, which is the normal source of input for the program.

FILE * stdout

The standard output stream variable, which is used for normal output from the program.

FILE * stderr

The standard error stream variable, which is used for error messages and diagnostics issued by the program.

 

Table 9.3:  Standard streams

fclose(stdout);

stdout = fopen ("standard-output-file", "w");

 

9.5  Links Story

 

9.5.1  Hard Links

int link(const char *oldname, const char *newname)

The link() function makes a new link to the existing file named by oldname, under the new name newname.

This function returns a value of 0 if it is successful and -1 on failure. In addition to the usual file name errors, for both oldname and newname, the following errno error conditions are defined for this function:

EACCES

You are not allowed to write to the directory in which the new link is to be written.

EEXIST

There is already a file named newname. If you want to replace this link with a new link, you must remove the old link explicitly first.

EMLINK

There are already too many links to the file named by oldname. (The maximum number of links to a file is LINK_MAX).

ENOENT

The file named by oldname doesn't exist. You can't make a link to a file that doesn't exist.

ENOSPC

The directory or file system that would contain the new link is full and cannot be extended.

EPERM

In the GNU system and some others, you cannot make links to directories. Many systems allow only privileged users to do so. This error is used to report the problem.

EROFS

The directory containing the new link can't be modified because it's on a read-only file system.

EXDEV

The directory specified in newname is on a different file system than the existing file.

EIO

A hardware error occurred while trying to read or write the to filesystem.

 

Table 9.4:  link() function

 

9.5.2  Symbolic Links

int MAXSYMLINKS

The macro MAXSYMLINKS specifies how many symlinks some function will follow before returning ELOOP. Not all functions behave the same and this value is not the same as a returned for _SC_SYMLOOP by sysconf. In fact, the sysconf result can indicate that there is no fixed limit although MAXSYMLINKS exists and has a finite value.

 

Table 9.5:  MAXSYMLINKS macro

int symlink(const char *oldname, const char *newname)

The symlink() function makes a symbolic link to oldname named newname.

The normal return value from symlink() is 0. A return value of -1 indicates an error. In addition to the usual file name prototype errors, the following errno error conditions are defined for this function:

EEXIST

There is already an existing file named newname.

EROFS

The file newname would exist on a read-only file system.

ENOSPC

The directory or file system cannot be extended to make the new link.

EIO

A hardware error occurred while reading or writing data on the disk.

 

Table 9.6:  symlink() function

 

int readlink(const char *filename, char *buffer, size_t size)

The readlink() function gets the value of the symbolic link filename. The file name that the link points to is copied into buffer. This file name string is not null-terminated; readlink() normally returns the number of characters copied. The size argument specifies the maximum number of characters to copy, usually the allocation size of buffer.

If the return value equals size, you cannot tell whether or not there was room to return the entire name.  A value of -1 is returned in case of error. In addition to the usual file name errors, following errno error conditions are defined for this function:

EINVAL

The named file is not a symbolic link.

EIO

A hardware error occurred while reading or writing data on the disk.

 

Table 9.7:  readlink() function

9.6    The Basic Of Disk File I/O

 

9.6.1    Opening And Closing A Disk File

 

  • Before we dive into the details, take note that the program examples presented here just for basic file I/O that applies to DOS and Linux.

  • For Windows, you have to study the Win32 programming that provides specifics file I/O and other related functions.  Here we do not discuss in details regarding the permission, right and authorization such as using Discretionary Access Control List (DACL) and Security Access Control List (SACL) implemented in Windows OS.

  • Furthermore for DOS type OS also, Microsoft uses Microsoft C (C-Runtime – CRT).  Nevertheless the concepts still apply to any implementation.

  • As explained before, in C, a FILE structure is a file control structure defined in the header file stdio.h.  A pointer of type FILE is called a file pointer, which references a disk file.

  • A file pointer is used by stream to conduct the operation of the I/O functions.  For instance, the following declaration defines a file pointer called fpter:

FILE  *fpter;

  • In the FILE structure there is a member, called the file position indicator, which points to the position in a file where data will be read from or written to.

 

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

FILE    *fptr;

if((fptr = fopen("test.txt","r")) == NULL)

{

   printf("Cannot open test.txt file.\n");

   exit(1);

}

Mode

Description

r

Open a file for reading.

w

Create a file for writing.  If the file already exists, discard the current contents.

a

Append, open or create a file for writing at the end of the file.

r+

Open a file for update (reading and writing).

w+

Create a file for update.  If the file already exists, discard the current contents.

a+

Append, open or create a file for update, writing is done at the end of the file.

rb

Opens an existing binary file for reading.

wb

Creates a binary file for writing.

ab

Opens an existing binary file for appending.

r+b

Opens an existing binary file for reading or writing.

w+b

Creates a binary file for reading or writing.

a+b

Opens or creates a binary file for appending.

 

Table 9.8:  Possible ways opening a file by various strings of modes in C

int    fclose(FILE    *stream);

fclose(fptr);

Computer system

Key combination

UNIX® systems

<return> <ctrl> d

IBM® PC and compatibles

<ctrl> z

Macintosh® - PowerPC

<ctrl> d

VAX® (VMS)

<ctrl> z

 

Table 9.9:  End-of-file (EOF) key combinations for various computer systems.

C:\BC5\Myproject\testing\

C:\BC5\Myproject\testing\tkk1103.txt

 

1.     // opening and closing a file example

2.     #include <stdio.h>

3.     // #include <stdlib.h>

4.      

5.     // SUCCESS = 0, FAIL = 1 using enumeration

6.     enum {SUCCESS, FAIL};

7.      

8.     int main (void)

9.     {

10.      FILE   *fptr;

11.      // the filename is tkk1103.txt and located

12.      // in the same folder as this program

13.      char filename[ ] = "tkk1103.txt";

14.   

15.      // set the value reval to 0

16.      int reval = SUCCESS;

17.      // test opening file for reading, if fail...

18.      if((fptr = fopen(filename, "r")) == NULL)

19.      {

20.           printf("Cannot open %s.\n", filename);

21.           reval = FAIL;      // reset reval to 1

22.      }

23.      // if successful do...

24.      else

25.      {

26.           printf("Opening the %s file successfully\n", filename);

27.           // the program will display the address where

28.           // the file pointer points to..

29.           printf("The value of fptr: 0x%p\n", fptr);

30.           printf("\n....file processing should be done here....\n");

31.           printf("\nReady to close the %s file.\n", filename);

32.           // close the file stream...

33.           if(fclose(fptr)==0)

34.           printf("Closing the %s file successfully\n", filename);

35.      }

36.      // for Borland…can remove the following pause and the library,

37.      // stdlib.h for other compilers

38.      // system("pause");

39.      return reval;

40.  }

 

40 lines: Output:

 

C file I/O opening and closing file stream

C file I/O opening and closing file stream failed open

 

printf("The value of fptr: 0x%p\n", fptr);

char    filename[ ] = "tkk1103.txt";

char    filename[ ] = "c:\\Temp\\tkk1103.txt";

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C file i/o related reading and digging:

 

  1. For C++ and MFC (Windows GUI programming) it is called Serialization and the topics are in Single Document Interface (SDI) and Multiple Document Interface (MDI).
  2. The source code for this Module is: C file input/output program source codes.
  3. Check the best selling C / C++ books at Amazon.com.
  4. Wide character/Unicode is discussed Character Sets, Unicode & Locale and the implementation using Microsoft C is discussed Windows Users & Groups C programming.
  5. Implementation specific information for Microsoft can be found Microsoft C Run-Time Tutorials and More Win32 Windows C Run-Time programming Tutorials.

 

 

 

 

 

 

 

 

|< C & C++ Pointers 3 | Main | C File I/O 2 >| Site Index | Download |

 


C File Input/Output:  Part 1 | Part 2 | Part 3 | Part 4 | Part 5