File I/OReading and Writing from a File
Lupoli.txt* ALWAYS starts here ----------------------------------->\n (end of line or whole line)----------------------------------------------------------------------------------------------------
eof – invisible marker placed on the file
When reading IN from a file
1. YOU ARE THE ONE WHO CREATED THE FILE!!!! So you know how it is laid out.
2. Since you are reading values IN, do NOT set any in your program!!!
When writing OUT to a file1
lastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstname
PROGRAM(reads in values)
1. YOU ARE THE ONE WHO CREATING THE FILE!!!! So you design how it is laid out.
2. Since you are writing values OUT, your program will set the values, then write!!!
Library Files needed for File I/O#include <stdio.h>
Opening a file (for input or output)FILE *infile = fopen("A:document.txt", mode);
‘in’ (infile) and “infile” denote we are reading IN from a file in this one line we are actually doing 2 things:
FILE *infile; // pointer to the file streamfopen("A:document.txt", mode) // opens file AND mode// book does it in 2 steps
Possible Modes“r” “w” “a”
Read from a file Write to a file Append a fileFile must be ALREADY
CREATEDWill write OVER a file
already createdWrite CREATE a file is
not present
Append CREATEs a file is not present
Will begin at END of a file if already created
2
lastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstnamelastname firstname
PROGRAM(write out values)
The syntax to open ANY file is as follows, you have several options: “A:/Lupoli.txt” “A:Lupoli.txt” “Z:\\Lupoli_class\\C\\test1.txt” IF YOU DO NOT SPECIFY DRIVE
o “Lupolistinks.txt”o will place beside .c file
normal “\” WILL NOT WORK!! Why won’t this work??
o “A:\nope.txt”
User input to open a filechar filename[100];
printf( “Please type the file to open: \n “);scanf(“%s”, filename);
FILE *infile = fopen(filename, “r”); // What type of file? Input/Output
FILE *outfile = fopen(filename, “w”); // What type of file? Input/Output
Notice “infile” “outfile” – so anything that I may have for infile, can be switched for an outfile
(inputs from a file) infile scanf (inputs from a keyboard)(outputs to a file) outfile printf (outputs to the monitor)
infile = read inoutfile = write out They can be ANYTHING you wish
3
Discussion on Streams
To check if a file was correctly opened must include stdlib.h for exit(1)
// after opening lineif(infile == NULL) or if(outfile == null){
printf( “The File was not successfully open.\n “);exit(1); // ends ENTIRE program!!!
} Closing a file (for input or output)
file MUST be closed when done important for outfile since it saves AND closes the file at the same time can reopen closed files
o will start from the beginning again can have several files opened
fclose(infile);fcloseall(); // closes ALL streams!!!
4
Reading from a file Syntax – almost same as a scanf, just fscanf instead
fscanf(infile, “% … ;fscanf(infile, “%d %d”, &x , &y); // you can also read multiple variables in one line
NOTICE: SPACE %’s when using fscanf!!!(had something weird happen when together)
Steps for reading from a file1. Identify data types of variables you will be reading from that file2. Next declare an uninitialized variable for each of them3. Then open the file for INPUT4. Check if the file was opened correctly5. Read in data from file6. Close file
Using the file example above “Lupoli.txt”, use the steps above, (except #5), to NEARLY complete your first function to read in from this file:(SLIP)(answer in cmsc104/code)
Reading different types of datareading a variable letter reading a variable int
char b; // will read a characterfscanf(infile, “%c” , &b);
int a; // will read a numberfscanf(infile, “%d”, &a);
reading a word – separated by “ “schar c[80]; // will read a “word” fscanf(infile, “%s”, c);
reading a sentence – a whole line in a text filechar line[80]; // will be big enough for an entire linefgets(line, 80, infile); // will read up to 100 chars, or until it reads a “\n”
Complete the exercise above, now that you know how to read from a file:
fscaf(infile, “%d %d %d %s %s….
Lupoli.txt23 41 a Luper
5
Reading (and writing) techniques There is a marker that tracks where you JUST read from in the file
Data in File Data types in file Code to read
23 41 a Luper Int, int, char, string fscanf(infile,“%d %d %s %s”, &getInt1 , &getInt2 , &getLetter , getWord);
One two three String, String, String fscanf(infile,“%s %s %s”, getWord1, getWord2, getWord3;
Lupoli Shawn 1600 Penn String, String, String (LONG)
char address[75];fscanf(infile,“%s %s”, getWord1, getWord2);fgets(address, 75, infile);
I wish Lupoli was easier String (LONG)char comment[175];fgets(address, 175, infile);
23 Lupoli 45 Bledsoe Int, String, Int, String fscanf(infile,“%d %s %d %s”, &getInt1 , getWord1 &getInt2 , getWord2);
Lohan Linday 23 1982
Lupoli A A D C
Differences in HOW to read dataSummer07.txtMiami
Read as Chars Read as Strings
1. How many char variables are needed to read in “Miami”?2. How many string variables are needed to read in “Miami”?3. Fill in the COMPLETE code to read in each typeWriting to a file
6
Syntax – almost same as a printf, just fprintf instead
fprintf(outfile, “% … \n “); // without “\n” it, the data will be printed on one linefprintf(outfile, “%d %d\n“, x , y); // you can also put multiple variables in one line
Writing different types of dataFILE *outfile = fopen("A:data.txt", “w”); // opening a file for output
writing a hard coded letter/number
writing a variable letter
fprintf(outfile, “f \n “);fprintf(outfile, “2 \n “);
char quit = ‘q’;fprintf(outfile, “%c \n“ , quit);
writing a hard coded sentence
writing a variable int
fprintf(outfile, “Hello Class\n “); int age = 23;fprintf(outfile, “%d \n”, age);
writing a variable sentencechar *sentence = “Welcome to C++ Programming\n “);fprintf(outfile, “%p \n”, sentence);
writing a char array (string)char y[5] = {"asje"}; fprintf(outfile, “%s \n”, y);
Dissecting and/or editing a line (PARSING!!) Determining/editing what you read in CHAR by CHAR!! #include <ctype.h>
char input[] = “Mr. Lupoli needs to get a life. And a real job”;
for(int i =0; i < strlen(input); i++) // non C99 mode{
if (isalpha(input[i]) > 0 ) { cout << “This LETTER was a letter of the alphabet\n”); }if (isdigit(input[i]) > 0 ) { cout << “This LETTER was number\n”); }if (ispunct(input[i]) > 0 ) { cout << “This LETTER was punctuation symbol\n”); }if(islower(input[i])) { input[i] = toupper(input[i]); } // makes line UPPER case
}Steps for writing to a file
7
1. Identify types of variables you will be writing OUT to that file, unless you want to hard code an output
2. Identify the ORDER you wish to place the data to the file3. Next declare an initialized variable for each of them4. Then open the file for OUTPUT5. Write data6. Close file
Where do I put the file to read in, or to output? That is up to you as a programmer OR up to the user (if you ask them) Simple way
o A:o F: (thumb)o Drive not specified (“document.txt”)
Means RIGHT beside the .c file you are creating
File Streams as Function Arguments a stream can be passed just like a variable
void read_scores(FILE *in) // prototype
void main( ){
FILE *infile = fopen(“A:test.txt”, “r”);
read_scores(infile); // this will pass “A:test.txt” into the function}
void read_scores(FILE *in) // function header{
int scores = 0;int input; while( fscanf( in, "%d", &input) != EOF ) // this command is IMPORTANT!!!{ // statements}
}Using a While loop to read data continually
8
// with the knowledge you have NOW, read in all values from “test.txt” below, use individual statements to read in each value (SLIP)
int score;
while( fscanf( infile, "%d", &input) != EOF ) // this command is IMPORTANT!!!{
scores = scores + input; // running total test.txt}
Draw a mock file (on paper) that will work with this while loop below:What data did I ignore (not use) in the code below?char firstname[20], lastname[20]; int score;char grade;
while( fscanf( infile, “%s %s %c %d”, first, last, &scores) != EOF ){
printf( "The Person %s %s had tests scores of: %d \n", first, last, grade, scores);}
89986654973498
9
Another example using a While loopvoid main( ){
Period8.txtFILE *nextinfile;
nextinfile = fopen("A:Period8.txt", “r”);
char last[20], first[20]; // reading in first and last name from the fileint T1, T2; // reading in the test scores
while( fscanf( nextinfile, “%s %s %d %d”, last, first, &T1, &T2) != EOF ){
printf( "The Person %s %s had tests scores of: %d %d \n", first, last, T1, T2 );}
fclose(nextinfile);}
Ignoring data in a file Remember you have to read in EACH piece of data, no skipping!! Don’t use it after you read it in!!
fscanf( nextinfile, “%d %s %s”, &number, last, first)
printf( "The Person you read in was %s %s", first , last);// notice, “number” WAS READ IN, but not used
Wegner Keith 70 60Wong Alex 30 10Allen Rodney 99 23Meehan Mike 23 56
10
What does token mean? Item separated by a space or \n (\r)
Actual File Token Count
Lupoli is da bomb!!Matt failed his midterm!!! Ha Ha!!!
46
Reading lines (LINES) in a file The while loop can also contain GETLINE
o Reads in a line at a time in a fileo NOT ALWAYS used!!!
Lupoli is da man.But he really needs a life.And a real job.
char line[80];
while(fgets(line, 80, infile)){
printf(“%s \n”, line); //will display EACH LINE of a file// do whatever you want to line here
}
Identifying strings inside a line read find string function
o returns a value > 0 IF a string IS found line < 0 if the string not found in line
using a while loop againo read in each lineo check the ENTIRE line for the target using FIND using an if condition
char line[80];char target[10] = “what”;
11
while(fgets(line, 80, infile)){
printf(“%s \n”, line); //will display EACH LINE of a file
if(strstr(line, target) != null) { printf( “target found\n”); }else { printf( “target not found, reading the next line\n”); }
}
Identifying characters inside a line read can use == for (char)acters using a while loop again
o read in each lineo then a for loop for go thru the entire line read in!!
check the ENTIRE line for the target using == using an if condition
char line[80];int count = 0;
while(fgets(line, 80, infile)){
printf(“%s \n”, line); //will display EACH LINE of a file
int i;for(i = 0; i < strlen(line); i++){
if(line[i] == ‘x’) { count++; }}
}
12
Again, the 3 strategies for reading in from a File
// 2 lines in this file
Sample FileIO programFILE *infile;infile.open(“H:FileIOLab.txt”);
opening statements Read in what??
char letter;fscanf(infile, "%s", &letter);
By letter
string word;fscanf(infile, "%s", &word);fscanf(infile, "%s", letter);
By word (string)
char line[80];infile.getline(line, 80, ‘\n’);fscanf(infile, "%s", &word);fscanf(infile, "%s", letter);
By line
infile.close(); Closing statements
What strategy would you use for each application? Check of which you would use.
By
lette
r
By
wor
d
By
line
Special Note:
+find the number of words per line+find the number of words in the file+find the number of letters per line+find the number of letters in the file+display words NOT “can”
FileIOLAB.txtA file can be read in many ways.
13
1 1
2
3
2
3
6
4
56 5
4
What NOT to do with File IO Read ALL patterned data in ONE pass in a loop
o used a while loopo but read ALL data in ONE iteration of the loop, so didn’t use the loop
No No #1Reading ALL data in the file
double num1,num2,num3,num4,num5,num6;
while (fscanf(infile, “%d %d %d %d %d %d %d”, &num1, &num2, &num3, &num4, &num5, &num6) != EOF){
average += num1 + num2 + num3 + num4 + num5 + num6;}
average = average/6;
// if the file ONLY HAS 6 values, how many times will the loop run??// what would happen if there were 18 values?? (Hint: average)
Corrected Versiondouble num, total = 0;int count = 0;
while ( fscanf(infile, "%d", &num) != EOF){
total += num; count++;}
average = total/count;
// How many items will “num” be used if reading a file with 10 values?// Why is count used??// Why is code more versatile??// Which version (no-no or corrected) has less code??
printf or scanfo YOUR NOT GETTING ANYTHING FOR THE KEYBOARD!!o I am NOT to see a scanf UNLESS
getting the file FROM THE USERo printf DOES NOT DISPLAY AN ENTIRE FILE
you need to read in the line from the file first and place into a string variable
then display THE VARIABLE Use a for loop to read the values inside the file.
14
o You might know how many values are there with the files I GIVE you but what if you didn’t know how many where going to be there, but
you knew the pattern?
No No #3Using a for loop to read data
for (int i = 0; i < 9; i++){
fscanf(infile, "%d", &num);total += num;
}
// how many values will this read?Corrected Version
// Create the reading loop using a while loop that will reads UNLIMITED values
fgets vs. fscanf use either depending on application!!! fgets
o grabs an ENTIRE lineo places into ONE variable
fscafo grabs individual itemso places in many variables
Options for reading in a line (based on application)fgets fscaf
while(fgets(line, 80, infile)){
}
while(fscanf(infile, "%d %d", &x, &y) != EOF){
}
15
Top Related