简体   繁体   中英

C++ text file I/O

This is a very simple question but wherever I look I get a different answer (is this because it's changed or will change in c++0x?):

In c++ how do I read two numbers from a text file and output them in another text file? Additionally, where do I put the input file? Just in the project directory? And do I need to already have the output file? Or will one be created?

You're probably getting different answers because there are many different ways to do this.

Reading and writing two numbers can be pretty simple:

std::ifstream infile("input_file.txt");
std::ofstream outfile("output_file.txt");

int a, b;
infile >> a >> b;
outfile << a << "\t" << b;

You (obviously) need to replace "input_file.txt" with the name of a real text file. You can specify that file with an absolute or relative path, if you want. If you only specify the file name, not a path, that means it'll look for the file in the "current directory" (which may or may not be the same as the directory containing the executable).

When you open a file just for writing as I have above, by default any existing data will be erased, and replaced with what you write. If no file by that name (and again, you can specify the path to the file) exists, a new one will be created. You can also specify append mode, which adds new data to the end of the existing file, or (for an std::fstream ) update mode, where you can read existing data and write new data.

If your program is a filter, ie it reads stuff from somewhere, and outputs stuff elsewhere, you will benefit of using standard input and standard output instead of named files. It will allow you to easily use the shell redirections to use files, saving your program to handle all the file operations.

#include <iostream>

int main()
{
    int a, b;
    std::cin >> a >> b;
    std::cout << a << " " << b;
}

Then use it from the shell.

> cat my_input_file | my_program > my_output_file

Put in the same folder as the executable. Or you can use a file path to point at it.

It can be created if it does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM