The course is part of this learning path
This course covers file input/output (file I/O). Being able to read from and write to secondary storage is important because often we want to keep some data persistently. By the end of this course, you will have the skills necessary to do this.
- Understand the fundamentals of both file input and file output and how to use both in tandem
- Use stream manipulators to make the structure of the data more organized
- Use dynamic memory, pointers, and classes to make more complex and interesting applications
- Beginner coders, new to C++
- Developers looking to upskill by adding C++ to their CV
- College students and anyone studying C++
To get the most out of this course, you should have a basic understanding of the fundamentals of C++.
In this lecture, we'll combine the input and output we've learned from the last two lectures. We will read data in from not one but two different files. One containing names and the other containing ages. Then we will write the ageName combinations to another file. The input files will be provided for you as names.txt and ages.txt as a part of the course resources. You just have to make sure you put them in the project directory underneath the solution where we create our project in Visual Studio. If you're using a different IDE from Visual Studio, put the files in the appropriate location for that IDE. Let's create a project called NamesAges. Create New Project, Empty Project, NamesAges. Let's make sure that we have the two input files names.txt and ages.txt in our project folder. So, I do have them available over here, ages and names. I'm going to copy those and I'm going to move up couple directories here and actually we have our project over here. Users prof jpb source repos and this is under names Ages right there. And then in the project folder, I'm going to paste them here. Now you don't have to add these to the project. These aren't like C++ or .ageFiles. So, we'll just leave those there. You'll notice that ages.txt has some ages in it and names.txt not surprising has some names in it. All right, now let's write some code. So, we need to create a main.cpp file and we're going to give it a skeleton to start include fstream. And we need string as well. Now we're reading in from two different files. So, we need Ifstream nameFile, for example, Ifstream ageFile and maybe ofstream outFile because we're printing the data into a single file. We need string tempName and tempAge and then we'll say Opening files and then maybe at the very end we'll say Done. And now we just need to fill in some code. So, we need to open the files of course. And for that after the declarations actually after opening files we'll put nameFile.open, names.txt. It'll look in the project folder. AgeFile.open, ages.txt and then outFile.open output.txt. So, this we can name whatever we want because that's what it's going to write to. And then after it's done or right before we print out Done, just to make sure nothing went wrong, we are going to close each of these. Now, what we're going to do after we've done that is we're going to do an error check after the Open. So, If not nameFile or not ageFile if those are invalid, we're going to say Problem opening one of the files bailing out" and we're going to return one because that's our error code that we return to the operating system. So, anything other than zero really and now we're going to loop through. While, not nameFile.eof and not ageFile.eof. We're going to loop. So, we need getline because we have a string from the nameFile, we're going to put each string and temp name as we go along and then the ageFile we can just use the stream extraction operator. And now for the outFile we're going actually write out to that file. So we'll say tempName, put a space in between the new tempAge and then endl. All right, of course let's give this a run to make sure it works. Says,Opening files done and let's check the actual files to make sure it worked. So, inside here, we see output.txt and it does in fact have all the information. The names and their ages. Cool, So, we pulled data from two different files that were written to secondary storage in this case one of my hard drives, we read them into main memory, wrote the data to an output file, one nameAge combination at a time. This is a very cool little application. Note that we could have just used one of the conditions for the why loops since they both have the same number of elements but it's a good precaution to have both in case one of the files is a different size than the other in which case it would stop with the smallest number. So, if there were 12 and 1 and 7 and the other would stop at the 7th name. So, we also performed an error check on nameFile a stream objects using the naught operator. So, when applied to those objects, the naught operator returns true if what's called the bad bit or the fail bit is set, which is a special bit indicating if the file is in some unusable state. If the file couldn't be opened or didn't exist, for example, bits like fail bit and bad bit are set. Using the naught operator is a good test to make sure that the object is valid. If it is not, we finished the program using a return 1. Why 1? This is a typical indicator the calling system that an error occurred. In other words that our program terminated after something went wrong. Now, nothing is really done about it in our context, but returning zero from main indicates a success. Well, again, any non zero usually one indicates there was a problem. Now, before we go on, I have a challenge for you. I'd like you to create a new project named TwiceFile. You will create a text file with a few images in it, say 5 or 8 or even more. However, many you really want and then you will put that in your project directory. Put one integer on each line for the sake of organization. Your program will read each integer, double its value and print it out to another file. So, pause the video and come back when you're done or if you need some help. How'd that go for you? Were you able to complete the project? Let's create the TwiceFile project, the text file for input and fill in some code. So, we're going to close this project. Let's create a new project, empty project called TwiceFile. And now we are going to create the files in it. So, let's go up to repose where I'm keeping my projects and TwiceFiles at the bottom there in the project folder. I can actually in windows, right click, go to new text document, and we need some sort of input here. So, we'll call it input.txt and we can put just, you know, five or more numbers in here, integers. So, 15, 20, 22, 6, 78, 99, 88. Here we go. Works for me. Now, of course we can create the file, add new item, the source file, of course, main.cpp. And now we're going to include iostream and fstream. All right, now we'll put ifstream in file. This time, I didn't capitalize file, doesn't really matter. Just trying to be consistent within a given file but within a given source file. Now we could do opening files. There we go. intFile.open the input.txt and outFile.open output.txt for output. And then later we of course need infile.close and outfile.close as well. In between these two is really where the magic happens. So, if not infile meaning that file doesn't exist or there's an error, error Opening file. Return 1, hopefully you remembered that part. While naught infile.eof infile to tempNum. And then what are we supposed to do? Print out double that number to the output file. OutFile I'm just going to in parentheses put tempNum times 2 and endl. There we go. I probably also want to put Done at the very bottom. There we go. Now, let's run it, make sure it works. Opening files and Done. We of course want to look at the output file. So, in here we had brought the input file over. Here is the output file. Open it and there are the numbers. RSo, if we look at the input file, we look at the input file next to the output file, that should be pretty obvious that each line is twice the other. Looks pretty good to me, awesome. So, we have been able to combine our skills with input and output and now we can use programs to transfer data into memory from file and then write the data from memory into another file. This is amazingly powerful and this is an incredibly powerful skill that you should have when you become a developer as being able to interact with files. C++ is no different. In the next lecture, we'll do our first project, which will involve reading some data and printing basic statistics related to that data. I'll see you there.
John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.