Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

File I/O in C: Reading and Writing Files, Study notes of Computer Science

An introduction to file input and output in c programming language. It explains how to declare a file pointer variable, connect it to a file using the fopen function, read and write data to the file, and close the file using the fclose function. The document also covers reading and writing characters, strings, and formatted data using various c functions.

Typology: Study notes

Pre 2010

Uploaded on 11/08/2009

koofers-user-a38
koofers-user-a38 🇺🇸

10 documents

1 / 17

Toggle sidebar

Related documents


Partial preview of the text

Download File I/O in C: Reading and Writing Files and more Study notes Computer Science in PDF only on Docsity! Basic Text File Access A file is a data target or data source that resides on disk and is completely independent from your C program. A file on disk exists whether or not your program is active in memory. It has a name of its own and a location of its own. In order to connect your C program to a file, you need to: 1) declare a file pointer variable in your program 2) connect that file variable to the actual disk file with an fopen function call 3) remember to break the connection when you are finished with the file by an fclose function call. In between steps 2 and 3, all communication between your program and the disk file is accomplished by referencing the file pointer variable and not by using the file’s disk name. The only place the file’s disk name is used is in the fopen function call. The fopen function determines the mode of communication that your program will use in communicating with the file. The file can be opened for reading ( using “r” mode) or opened for writing ( using “w” mode). Let’s assume that a text file named data.txt resides in the default directory on your disk drive. You want to open this file for reading (as an input source for your program). First, declare a file pointer variable: FILE * infile; Then in your code section, make an appropriate call to the fopen function. infile = fopen(“data.txt”, “r”); If your function call fails for any reason (misspelled name etc) the infile pointer will have the NULL value. If it succeeds, the value will not be NULL. This means that the open call can be placed in an if statement that checks for failure and notifies the person running your program as follows: Files in C - 1 Files and Libraries in the C Programming Language The above will gracefully terminate your program if the input file is not opened correctly and continue running if it is opened successfully. Assuming it opened correctly, your program can now communicate with the file by referencing the file pointer infile. Example To read a string variable called name from the file, fscanf(infile, “%s”, name); should work. There are other C functions that can read from a file opened in read mode. Most are listed in <stdio.h> The use of fscanf is identical to that of scanf except for the new first argument. The first argument to fscanf must be a file pointer. After you finish processing the file, close it with an appropriate call to the fclose function. The fclose function takes the file pointer as its only argument. fclose (infile); Now, suppose you want to open a file named output.txt to receive data from your program. Once again, you need a file pointer variable in your program to associate with the file. FILE * outfile; and an appropriate call to the function fopen to make the connection: Files in C - 2 if ( NULL == (infile = fopen (“data.txt”, “r”))) { printf(“\nError opening input file\n”); exit(0); } if ( NULL == (outfile = fopen (“output.txt”, “w”))) { printf(“\nError opening output file\n”); exit(0); } char filename[20], *temp; FILE *infile, *outfile; printf("This program removes comments from a file.\n"); while (TRUE) { printf("File name: "); scanf("%s", filename); infile = fopen(filename,"r"); if (infile != NULL) break; printf("File %s not found. Try again.\n", filename); } temp = tmpnam(NULL); outfile = fopen(temp, "w"); if (outfile == NULL) printf("Error: Can't open temporary file.\n"); else { CopyRemovingComments(infile,outfile); fclose(infile); fclose(outfile); if (remove(filename) != 0|| rename(temp,filename) != 0) printf("Unable to rename temporary file."); } } void CopyRemovingComments (FILE *infile, FILE *outfile) { int ch, nch; int commentFlag; printf("Inside Copy function\n"); commentFlag = FALSE; while ( ( ch = getc(infile) ) != EOF) { if (commentFlag) { if (ch == '*'){ nch = getc(infile); if (nch == '/') commentFlag = FALSE; else ungetc(nch,infile); Files in C - 5 } } else { if (ch =='/') { nch = getc (infile); if (nch == '*') commentFlag = TRUE; else ungetc(nch, infile); } if (!commentFlag) putc (ch,outfile); } } } Formatted I/O The printf function comes in three different forms: printf(control string, …); fprintf(output stream, control string, …); sprintf(character array, control string, …); The scanf function comes in three different forms: scanf(control string, …); fscanf(input stream, control string, …); sscanf(character array, control string, …); Libraries and Interfaces  An interface is the boundary between the implementation of a library and programs that use that library (i.e. its clients) .  The purpose of an interface is to provide each client with the information it needs to use the library without revealing the details required by the implementation.  In C, an interface is represented by a header file, which traditionally has the same name as the file that implements it with the .c extension replaced by .h. Files in C - 6 For example, you created a collection of functions that you want to make available to clients as a library. You need to create two files:  an interface (mylib.h)  contains only the functions prototypes  corresponding implementation (mylib.c)  Putting the prototypes in the interface makes them available to clients and is called exporting those functions.  Interfaces can export :  function prototypes  data types  constants  In computer science the term package is used to describe the software that defines a library. That is:  a .h file, and  corresponding .c file Files in C - 7 Any source file that makes use of the definitions exported by the library The interface contains only the information about the library that its clients need to know. The implementation contains the code to make the library work, the details of which are not of interest to clients. client.c mylib.h mylib.c A user defined library: The random.c implementation /* * File: random.c * -------------- * This file implements the random.h interface. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include “random.h” /* * Function: RandomInteger * ----------------------------------- * This function begins by using rand to select an integer in the * interval [0,RAND_MAX] and then converts it to the desired range * by applying the following steps: * * 1. Normalize the value to a real number in interval[0,1) * 2. Scale the resulting value to the appropriate range size * 3. Truncate the scaled value to an integer * 4. Translate the integer to the appropriate starting point. */ int RandomInteger(int low, int high) { int k; double d; d = (double) rand() / ((double)RAND_MAX + 1); k = (int) (d*(high – low + 1)); return (low + k); } (continued on next page) Files in C - 10 /* * Function: RandomReal * -------------------- * The implemetation of RandomReal is similar to that of RandomInteger, * without the truncation step. */ double RandomReal(double low, double high) { double d; d= (double) rand()/(double)RAND_MAX + 1; return (low + d * (high – low)); } /* * Function: RandomChance * ---------------------- * This function uses RandomReal to generate a real number in the * interval [0,1) and then compares that value to p. */ int RandomChance(double p) { return(RandomReal(0,1) < p); } /* * Function: Randomize * ------------------- * This function operates by setting the random number seed to the * current time. */ void Randomize(void) { srand((int) time(NULL)); } Files in C - 11 Basic Text File Access A file is a data target or data source that resides on disk and is completely independent from your C program. A file on disk exists whether or not your program is active in memory. It has a name of its own and a location of its own. In order to connect your C program to a file, you need to: 1) declare a file pointer variable in your program 2) connect that file variable to the actual disk file with an fopen function call 3) remember to break the connection when you are finished with the file by an fclose function call. In between steps 2 and 3, all communication between your program and the disk file is accomplished by referencing the file pointer variable and not by using the file’s disk name. The only place the file’s disk name is used is in the fopen function call. The fopen function determines the mode of communication that your program will use in communicating with the file. The file can be opened for reading ( using “r” mode) or opened for writing ( using “w” mode). Let’s assume that a text file named data.txt resides in the default directory on your disk drive. You want to open this file for reading (as an input source for your program). First, declare a file pointer variable: FILE * infile; Then in your code section, make an appropriate call to the fopen function. infile = fopen(“data.txt”, “r”); If your function call fails for any reason (misspelled name etc) the infile pointer will have the NULL value. If it succeeds, the value will not be NULL. This means that the open call can be placed in an if statement that checks for failure and notifies the person running your program as follows: Files in C - 1 Files and Libraries in the C Programming Language The above will gracefully terminate your program if the input file is not opened correctly and continue running if it is opened successfully. Assuming it opened correctly, your program can now communicate with the file by referencing the file pointer infile. Example To read a string variable called name from the file, fscanf(infile, “%s”, name); should work. There are other C functions that can read from a file opened in read mode. Most are listed in <stdio.h> The use of fscanf is identical to that of scanf except for the new first argument. The first argument to fscanf must be a file pointer. After you finish processing the file, close it with an appropriate call to the fclose function. The fclose function takes the file pointer as its only argument. fclose (infile); Now, suppose you want to open a file named output.txt to receive data from your program. Once again, you need a file pointer variable in your program to associate with the file. FILE * outfile; and an appropriate call to the function fopen to make the connection: Files in C - 2 if ( NULL == (infile = fopen (“data.txt”, “r”))) { printf(“\nError opening input file\n”); exit(0); } if ( NULL == (outfile = fopen (“output.txt”, “w”))) { printf(“\nError opening output file\n”); exit(0); } char filename[20], *temp; FILE *infile, *outfile; printf("This program removes comments from a file.\n"); while (TRUE) { printf("File name: "); scanf("%s", filename); infile = fopen(filename,"r"); if (infile != NULL) break; printf("File %s not found. Try again.\n", filename); } temp = tmpnam(NULL); outfile = fopen(temp, "w"); if (outfile == NULL) printf("Error: Can't open temporary file.\n"); else { CopyRemovingComments(infile,outfile); fclose(infile); fclose(outfile); if (remove(filename) != 0|| rename(temp,filename) != 0) printf("Unable to rename temporary file."); } } void CopyRemovingComments (FILE *infile, FILE *outfile) { int ch, nch; int commentFlag; printf("Inside Copy function\n"); commentFlag = FALSE; while ( ( ch = getc(infile) ) != EOF) { if (commentFlag) { if (ch == '*'){ nch = getc(infile); if (nch == '/') commentFlag = FALSE; else ungetc(nch,infile); Files in C - 5 } } else { if (ch =='/') { nch = getc (infile); if (nch == '*') commentFlag = TRUE; else ungetc(nch, infile); } if (!commentFlag) putc (ch,outfile); } } } Formatted I/O The printf function comes in three different forms: printf(control string, …); fprintf(output stream, control string, …); sprintf(character array, control string, …); The scanf function comes in three different forms: scanf(control string, …); fscanf(input stream, control string, …); sscanf(character array, control string, …); Libraries and Interfaces  An interface is the boundary between the implementation of a library and programs that use that library (i.e. its clients) .  The purpose of an interface is to provide each client with the information it needs to use the library without revealing the details required by the implementation.  In C, an interface is represented by a header file, which traditionally has the same name as the file that implements it with the .c extension replaced by .h. Files in C - 6 For example, you created a collection of functions that you want to make available to clients as a library. You need to create two files:  an interface (mylib.h)  contains only the functions prototypes  corresponding implementation (mylib.c)  Putting the prototypes in the interface makes them available to clients and is called exporting those functions.  Interfaces can export :  function prototypes  data types  constants  In computer science the term package is used to describe the software that defines a library. That is:  a .h file, and  corresponding .c file Files in C - 7 Any source file that makes use of the definitions exported by the library The interface contains only the information about the library that its clients need to know. The implementation contains the code to make the library work, the details of which are not of interest to clients. client.c mylib.h mylib.c A user defined library: The random.c implementation /* * File: random.c * -------------- * This file implements the random.h interface. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include “random.h” /* * Function: RandomInteger * ----------------------------------- * This function begins by using rand to select an integer in the * interval [0,RAND_MAX] and then converts it to the desired range * by applying the following steps: * * 1. Normalize the value to a real number in interval[0,1) * 2. Scale the resulting value to the appropriate range size * 3. Truncate the scaled value to an integer * 4. Translate the integer to the appropriate starting point. */ int RandomInteger(int low, int high) { int k; double d; d = (double) rand() / ((double)RAND_MAX + 1); k = (int) (d*(high – low + 1)); return (low + k); } (continued on next page) Files in C - 10 /* * Function: RandomReal * -------------------- * The implemetation of RandomReal is similar to that of RandomInteger, * without the truncation step. */ double RandomReal(double low, double high) { double d; d= (double) rand()/(double)RAND_MAX + 1; return (low + d * (high – low)); } /* * Function: RandomChance * ---------------------- * This function uses RandomReal to generate a real number in the * interval [0,1) and then compares that value to p. */ int RandomChance(double p) { return(RandomReal(0,1) < p); } /* * Function: Randomize * ------------------- * This function operates by setting the random number seed to the * current time. */ void Randomize(void) { srand((int) time(NULL)); } Files in C - 11 Constructing a client program: Craps Problem specification: We want to develop an algorithm/program that will allow us to play the game of craps. Problem analysis: Need to know how to play craps.  A player rolls (throws) two dice.  If the sum of the two dice is 7 or 11 on the first throw, the player wins.  If the sum of the two dice is 2, 3, or 12 on the first throw, the player loses.  If the sum of the two dice is 4, 5, 6, 8, 9, or 10 on the first throw, then that sum becomes the player’s point. To win, the player must continue rolling the dice until they make their point. The player loses by rolling a 7 before making the point. Examples of playing the game: (1) Player rolls 6 + 5 = 11 Player wins! (2) Player rolls 6 + 6 = 12 Player loses. (3) Player rolls 4 + 6 = 10 Point is 10 Player rolls 2 + 4 = 6 Player rolls 3 + 3 = 6 Player rolls 4 + 6 = 10 Player wins! (4) Player rolls 1 + 3 = 4 Point is 4 Player rolls 1 + 4 = 5 Player rolls 5 + 4 = 9 Player rolls 4 + 6 = 10 Player rolls 6 + 3 = 9 Player rolls 5 + 2 = 7 Player loses English algorithm: (1) Roll two dice and get their sum. (2) Check the sum and determine the status of the game  Game status = 1; player wins  Game status = 2; player loses  Game status = 0; game in progress, player tries to make the point. (3) If game status is 0, continue rolling dice until game status is 1 or 2. (4) Print the results of the game. Files in C - 12 printf(“You made your point. You win.\n”); else printf(“You rolled a seven. You lose.\n”); } } /* * Function: TryToMakePoint * ------------------------ * This function is responsible for the part of the game during which * you roll the dice repeatedly until you either make your point or * roll a 7. The function returns true or false. */ int TryToMakePoint(int point) { int total; while (TRUE) { total = RollTwoDice(); if (total == point) return (TRUE); if (total == 7) return (FALSE); } } /* * Function: RollTwoDice * --------------------- * This function rolls two dice and returns their sum. As part of the * implementation the result is displayed on the screen. */ int RollTwoDice (void) { int d1, d2, total; printf(“Rolling the dice ... \n”); d1 = RandomInteger(1,6); d2 = RandomInteger(1,6); total = d1 + d2; printf(“You rolled %d + %d = %d\n”, d1,d2, total); return total; } Files in C - 15 Modular Development Program structured as a single module: Files in C - 16 main() { ProcA(); ProcB(); } void ProcA(void) { ... } void ProcB(void) { ... } program.c Program divided into separate modules: Files in C - 17 #include “module1.h” #include “module2.h” main() { ProcA(); ProcB(); } void ProcA(void); void ProcB(void); #include “module1.h” void ProcA(void) { ... } #include “module2.h” void ProcB(void) { ... } module1.h module2.h module1.c module2.c main.c
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved