使用c ++中的read方法读取文件内容 [英] Reading file content using read method in c++

查看:450
本文介绍了使用c ++中的read方法读取文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在输出中使用read方法显示文本文件的所有内容。

我使用下面的代码执行此操作:



但是在文件内容的末尾显示了一些特殊字符,您可以在下面看到:



I want to show all content of a text file using "read" method in output.
I have used code below for doing this:

But it was shown some special characters in the end of file content which you can see below:

ÍÍýýýý««««««««îþîþîþ





这是什么原因?我不想要这个。



我尝试过:





What’s the reason? I don’t want this.

What I have tried:

#include
#include
#include
using namespace std;

int main(){

ifstream myfile;
myfile.open("c:\\new.txt", ios::in);
myfile.seekg(0, ios::end);
int filesize = myfile.tellg();
char *content = new char[filesize + 1];
myfile.seekg(0, ios::beg);
myfile.read(content, filesize);
content[filesize] = '\0';
cout << content;
delete[] content;
myfile.close();

_getch();
return 0;

}

File content:
this is a test
this is a test

推荐答案

那是因为你没有添加一个空字符来告诉 cout 缓冲区末尾的位置。尝试:

That is because you have not added a null character to tell cout where the end of the buffer is. Try:
int filesize = myfile.tellg();
char *content = new char[filesize + 1];  // add space for null character
myfile.seekg(0, ios::beg);
myfile.read(content, filesize);
content[filesize] = '\0';    // mark end of text



备注此代码已过度简化。


Note this code is over simplified.


问题出现是因为您正在读取文本文件,并且因为 fstream 处理它替换CR-的内容具有单个换行符'\ n'的LF序列。因此,您的实际内容将短于磁盘上文件的长度。您应该使用 getline 方法依次读取文件的每一行,或将文件类型设置为二进制(参见 ios_base :: openmode [ ^ ])。
The problem occurs because you are reading a textfile, and as fstream processes the content it replaces CR-LF sequences with the single newline character '\n'. Thus your actual content will be shorter than the length of the file on disk. You should use the getline method to read each line of the file in turn, or set the file type to binary (see ios_base::openmode[^]).


这篇关于使用c ++中的read方法读取文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆