Tutorial - C / C++ - Read/Write files


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
This tutorial will demonstrate how to read in a file and also output the details to another file. The headers
fstream and iostream
basically include details on File-streaming (fstream) and In-Output-Streaming (iostream).

I have attached the code within a zip file with the required input file as well.

The namespace denotes which area are you in, for example : maths:algebra would mean you are doing maths and with the topic of Algebra, within the c/c++ example std::ifstream means that the namespace is std and the function/variable is ifstream.

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

Below is the code
---
#include <stdio.h>
#include <fstream>
#include <iostream>

using namespace std;// use the namespace (e.g. instead of putting std::ifstream you just need to put fstream.)

int main(void)
{
       char InStr[100];
       ifstream InFile("countrys.txt",ios::in);// infile
       ofstream OutFile("outcountrys.txt", ios::out);// outfile

       while (InFile.getline(InStr,100))// while reading each line within the file
       {
              printf("%s\n", InStr);// output the read line to the console
              OutFile << “value = “ << InStr << “\n";// output to the outfile
}
       InFile.close();//close down both files.
       OutFile.close();
       return 0;
}
---

If you save this as readfile.cpp and also create a countrys.txt file with what ever text you like, e.g.
United Kingdom
France
Germany
United States
etc.

Once you have compiled the program and execute the program, it will look for the file countrys.txt within the same directory as the program executable and also create outcountrys.txt within the same directory (it will write over the file if there is one present). Then within the while loop it will read the input file line by line and output to the screen what has been read and also output to the output file “value = “ readline.

Of course to finish off to close down the files and return back to the console.
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search