Home  >  Article  >  Backend Development  >  C++ implements line-by-line reading of strings in txt files and copying of file text

C++ implements line-by-line reading of strings in txt files and copying of file text

little bottle
little bottleOriginal
2019-04-27 13:58:096840browse

This article mainly talks about using C to read the strings in the txt file line by line and copy the file text. It has certain reference value. Interested friends can learn about it. I hope it will be helpful to your study.

Read the string in the txt file line by line, the code is as follows

#include <fstream>
#include <string>
#include <iostream>
using namespace std; 
int main()
{
	ifstream in("1.txt");
	string filename;
	string line;
	if(in) // 有该文件
	{
		while (getline (in, line)) // line中不包括每行的换行符
		{ 
			cout << line << endl;
		}
	}
	else // 没有该文件
	{
		cout <<"no such file" << endl;//温馨小提示,木有此文件
	}
	return 0;
}

Copy the file text, copy the content in 1.TXT to 2.TXT, the code is as follows:

#include <fstream>
#include <string>
#include <iostream>
using namespace std;
void fileCopy(char *file1, char *file2)
{
	// 最好对file1和file2进行判断
	ifstream in(file1);
	ofstream out(file2);
	string filename;
	string line;
	while (getline (in, line))
	{ 
		out << line << endl;
	}
}
int main()
{
	fileCopy("1.txt", "2.txt");
	return 0;
}

The above program can only be used for text files (not just .txt) and is not suitable for other types of files.

The code in this article has been tested under Windows/VC 6.0, and there is no problem under Linux/g.

But please be sureAttentionThe difference between Linux and Windows file formats:

1. When the code on Linux reads the Windows file format, Each line of the read result will have one more \r.

2. When the code on Windows reads the Linux format file, the read result will show only one line.

Related tutorials: C Video Tutorial

The above is the detailed content of C++ implements line-by-line reading of strings in txt files and copying of file text. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn