Docsity

C Programming: Working with Text Files, Slides of Computer Programming

Toggle sidebar
bg1
3/2/00 C Programming 2
Files
• Files can permanently store information on
hard disk
• In general there are two types of data files
– Text files (which can be opened and read by any
test editor – a C file itself is an example of a text file)
– Binary files which only a computer program can
successfully open and access
• C programs can use either type of file to store
information but in this lecture we will only focus
on using text files
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download C Programming: Working with Text Files and more Slides Computer Programming in PDF only on Docsity!

3/2/

C Programming

2

Files

•^

Files can permanently store information onhard disk

-^

In general there are two types of data files–^

Text files (which can be opened and read by anytest editor – a C file itself is an example of a text file)

Binary files which only a computer program cansuccessfully open and access

•^

C programs can use either type of file to storeinformation but in this lecture we will only focuson using text files

3/2/

C Programming

3

FILE variable

•^

A new variable FILE is introduced for accessingfiles using C programs– (NOT File, file or anything else!)

-^

This type is defined in stdio.h

-^

This variable is used internally by a C programto store all the information it needs tosuccessfully open, access and close files– We only need to think of this variable as the

computer’s way of knowing where in the file it iscurrently looking

3/2/

C Programming

5

The type

FILE

is defined in

stdio.h

It is a structure that holds various kinds ofinformation about the file, such as size.The

file pointer

will be used with all other

functions that operate on the file and itmust never be altered or the object it pointsto.

3/2/

C Programming

6

Functions for Handling Files

•^

C supports functions to– open files (fopen), and– close files (fclose)

-^

Files must be opened before any attempt ismade to read information from them or writeinformation to them

-^

It is also good practice to close the file after yourprogram is finished reading information from it orwriting information to it

3/2/

C Programming

8

fopen Function

•^

The fopen function ATTEMPTS to open a filewhose name is stored in a character string

-^

The typical syntax of this function is:

-^

file_pointer = fopen(

name

,^

mode

name

is typically a character array containing the

name of the text file being opened

mode

is a text string which contains alphabetic

characters that describe the reason for opening thefile

•^

When using text files, it is recommended thatyou give your data files names of the formfile_name.dat, file_name.txt or file_name.log

3/2/

C Programming

9

Mode

Meaning

r^

Open a text file for reading

w

Create a text file for writing

a^

Append to a text file

rb

Open a binary file for reading

wb

Open a binary file for writing

ab

Append to a binary file

r+

Open a text file for read/write

w+

Create a text file for read/write

a+

Append or create a text file for read/write

r+b

Open a binary file for read/write

w+b

Create a binary file for read/write

a+b

Append a binary file for read/write

3/2/

C Programming

11

Checking fopen

-^

After attempting to open a file, your C program shouldALWAYS check whether the file was openedsuccessfully or not– Perhaps the file does not exist!– Perhaps the file was opened to write to but there is no

more free capacity on your disk drive

-^

This can be done by checking the value stored in the filepointer

-^

If this value is a special code (used only for pointers)called NULL, it means that there is nothing stored in thepointer variable and hence the file opening attempt wasNOT successful

3/2/

C Programming

12

Example

-^

An example of asking the user for a file name and then opening atext file to read information from itvoid main(void){

char file_name[100];FILE *file_pointer=NULL;printf(“\nPlease enter file name : “);scanf(“%s”,file_name);file_pointer=fopen(file_name,”r”);if (file_pointer!=NULL){

…………………….. (file was opened)

}

}

3/2/

C Programming

14

fclose Function

•^

The function

fclose

is used to close a previously

(successfully) opened file when your program isfinished using it

-^

The syntax for using this function is very simple

fclose(file_pointer);

•^

Any open files are automatically closed whenyour C program finishes but it is a good habit toto close files as soon as your program no longerneeds them to be open

3/2/

C Programming

15

Reading From a File

  • Steps
    • Declare FILE variable– Open the file (read mode)– Read from the file– Close the file

3/2/

C Programming

17

File Reading Example

  • Sum the numbers in a file

#include <stdio.h>void main () {

int num, sum = 0;FILE *inptr;if ((inptr = fopen(“infile”, “r”)) != NULL) {

while(fscanf(inptr, “%d”, &num) != EOF)

sum += num;

fclose(inptr);printf(“The sum of the numbers is %d\n”,sum);

}

}

3/2/

C Programming

18

Read from the File

  • One character at a time
    • Format: c = getc(fptr)
      • getc reads from file pointer (fptr) and returns a

character

  • Similar to getchar
    • Example
      • while ((c = getc(infileptr)) != EOF)
        • Continues reading characters until it reaches the end of

the file

  • c = fgetc(fptr) does the same thing

3/2/

C Programming

20

Writing to a File

  • Steps
    • Declare FILE variable
      • Same as before
        • Open the file (write mode)– Write to the file– Close the file
          • Same as before

3/2/

C Programming

21

Open the File

  • Format: fptr = fopen(“file”,”w”);
    • E.g, infileptr = fopen(“my_file”,”w”);
      • Creates new file
        • Overwrites file if it exists
          • Starts writing at the beginning of the file
            • fopen(“file”, “a”) appends a file
              • Creates new file if it doesn’t exist
                • Starts writing from the beginning
                  • Starts writing at the end of an existing file