0% found this document useful (0 votes)
77 views6 pages

Lecture 7 Text Files and Files of Records

The document discusses different file types for storing data in C programming, including text files, CSV files, and binary files of records. It provides examples of opening, reading from, and writing to each file type. Key functions discussed include fopen(), fread(), fwrite(), fgets(), fprintf().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views6 pages

Lecture 7 Text Files and Files of Records

The document discusses different file types for storing data in C programming, including text files, CSV files, and binary files of records. It provides examples of opening, reading from, and writing to each file type. Key functions discussed include fopen(), fread(), fwrite(), fgets(), fprintf().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming in C

by
Roger Y. Mawoh
13 July 2020
_________________________
© 2020, Roger Y. Mawoh
All rights reserved. No part of these notes may be reproduced or transmitted in any form, or by any
means electronic or mechanical, including photocopying, recording or any information
storage or retrieval system, without the prior written permission of the author. Permission is hereby
granted to the applicable batches of students taking any course in Computer Science at the
University of Buea, Cameroon, to use this document for academic purposes only, and in as many
copies as desired.
_________________________

Lecture 7:Text files and files of record


 Text files
 CSV files
 Files of records
 Summary

 So far we have done a lot of programming and data handling, but the data was only stored in
variables in main memory as the program was executing. When the program terminates, the
contents of the variables are lost. We need some way of storing data in backing store. This
can be done using text files, CSV files, binary files or databases.

 Text Files
 A text file consists of a sequence of printable characters organized into lines, each of which is
terminated by an end of line marker.
 A text file can be opened and read in a text editor.
 When using text files, you read or write a line of text at a time as string.
 You open a text file for reading or writing. You can have more than one file open at any one
time, such as one for reading and another one for writing.
 The next example reads five lines of text from the keyboard and saves them in a text file.
 The following example reads the text file and displays the lines of text on the console.
 Writing on a text file (file0.c)
//includes
#include <stdio.h>

int main(void)
{
// Open text file
FILE *ptr1 = fopen("file1.txt", "w");

int count;
char textstring[40];

char ch;
if (!ptr1)
{
return 1;
}

for(count = 1; count <= 5; count++){


printf("Input line number %d: ", count);
gets(textstring);
fprintf(ptr1, "%s\n", textstring);
}

// Close file
fclose(ptr1);

return 0;
}

 Reading text from a file (file1.c)
//includes
#include <stdio.h>

int main(void)
{
// Open CSV file
FILE *ptr1 = fopen("file1.txt", "r");

char textstring[1000];

if (!ptr1)
{
return 1;
}

while((fgets(textstring, 1000, ptr1)) != NULL){


printf("%s", textstring);
}

// Close file
fclose(ptr1);
fclose(ptr1);

return 0;
}
 CVS files
 A coma-separated values (CVS) file is a text file with one record per line and the field of each
record separated by commas. CVS files are popular as data files for mail-merge programs.
 If you wish to create a CVS file more simply, you can create a new text file. Output each record
using a separate statement. Put a comma between each field.
 phonebook.c:
//includes
#include <stdio.h>

int main(void)
{
char name[20];
char number[10];
// Open CSV file
FILE *file = fopen("phonebook.csv", "a");
if (!file)
{
return 1;
}

// Get name and number


printf("Name: ");
scanf("%s", name);
printf("Number: ");
scanf("%s", number);

// Print to file
fprintf(file, "%s,%s\n", name, number);

// Close file
fclose(file);

return 0;
}

 Files of records
 Files of records are also known as binary files. A file of records usually contains multiple data
types. Data types other than strings and characters are stored in internal format and cannot be
displayed in a meaningful way in a text editor, which can only interpret codes (ASCII or
Unicode).
 You need to know the organization of record in a binary file to be able to read it.
 This example consists of two programs for each programming language. The first read values
for account records from the keyboard and saves them in a file of records. The second reads the
file of records and display them on the console.
 You may wish to read records from a file into an array of records while the program is running
and store the contents of the array back into the file before the program terminates.
 Writing to a binary file (account0.c)
//includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// a structure to read and write


struct customer {
char fname[20],lname[20];
int acct_num;
float acct_balance;
};

void main ()
{
FILE *outfile;
struct customer input;
char answer;

// open Accounts file for writing


outfile = fopen ("accounts.dat","w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}

// instructions to user
printf("Enter \"stop\" for First Name to end program.");

// endlessly read from keyboard and write to file


do
{
// prompt user
printf("\nFirst Name: ");
scanf ("%s", input.fname);
// exit if no name provided
if (strcmp(input.fname, "stop") == 0)
exit(1);
// continue reading from keyboard
printf("Last Name : ");
scanf ("%s", input.lname);
printf("Acct Num : ");
scanf ("%d", &input.acct_num);
printf("Balance : ");
scanf ("%f", &input.acct_balance);

// write entire structure to Accounts file


fwrite (&input, sizeof(struct customer), 1, outfile); fflush(stdin);
printf("Do you want to add another record (y/n): ");
scanf("%c",&answer);
}while((answer == 'y')||(answer == 'Y'));

return 0;
}
 The function to write a struct in C is fwrite().
fwrite (*struct, size, count, file)

 The first argument is the location of the structure to write. The second argument is the byte size
of that structure. The third argument is how many of those structures to write. The fourth
argument is the output file.
 So, given this declaration,
struct account my_acct;

 we could write the entire structure with this command:


fwrite (&my_acct, sizeof (struct account), 1, outfile)

 Given an array of 15 of these structures,


struct account my_acct[15];

 we could write all 15 elements:


fwrite (&my_acct, sizeof (struct account), 15, outfile)

 Reading from a binary file (account1.c)
//includes
#include <stdio.h>
#include <stdlib.h>

struct customer {
char fname[20],lname[20];
int acct_num;
float acct_balance;
};

void main ()
{
FILE *infile;
struct customer input;

/*** open the accounts file ***/


infile = fopen ("accounts.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}

while (fread (&input, sizeof(struct customer), 1, infile))


printf ("Name = %10s %10s Acct Num = %8d Balance = %8.2f\n",
input.fname, input.lname, input.acct_num, input.acct_balance);

return 0;
}
 The function to read a structure in C is fread().
fwrite (*struct, size, count, file)

 So, the arguments to fread() are the same as fwrite().

Questions
1- Read from an existing text file and display the contents of the file on the console. You can read a text file in any text
editor.
2- Expand your program from Question 1 to count the number of lines read from the file and display this total.

3- Expand your program from Question 2 to count the number of words read. HINT: a word terminates with a space,
punctuation marks or the end of line.

4- Declare a record type for student details and store in a variable of this type one student’s details entered at the
keyboard. Before the program terminates, it should save the record to a binary file.

5- Expand your program from Question 4 to read several students’ records into an array of records and store the contents
of the array into a file before the program terminates.

 Summary
In this lesson you have covered

 The difference between a text file, a CSV file and a binary file of records
 How to read from and write to a text file
 Reading records from a binary file
 Writing records to a binary file

You might also like