c++ txt 文件读写 读入文件到一个变量

2025-03-01 13:11:40
推荐回答(5个)
回答1:

把文件存储到一个变量里?
这么做不好,
因为不知道文件有多大,
在内存中应该申请多大的内存空间,
无法确定。
要做文件操作的话,
一般情况下是开辟出一块固定大小的内存缓冲区,
通过这个缓冲区来处理文件中的内容。

剩下的就是文件操作,
没什么难的了。

回答2:

#include
#include

using namespace std;

// 获取文件长度
long file_length(char const *path)
{
ifstream file(path, ios::binary);

if (!file)
{
cerr << "Can not open the file!" << endl;
return 0;
}
file.seekg(0L, ios::end);
streampos end = file.tellg();
file.close();
return long(end);
}

int main(int argc, char* argv[])
{
long length = file_length("test.txt");;
char *content;
ifstream infile("test.txt");

if (!infile)
{
cerr << "Can not open the file!" << endl;
return -1;
}

content = new char[length+1];
memset(content, 0, length+1);
infile.read(content, length);
infile.close();
cout << content << endl;
delete[] content;
return 1;
}

回答3:

你不用使用C++自己编程。你可以用WORD自己搞定。如果是考试题让你这么做的话。那就没招了。混个分,闪人。如果是自己用的话 我可以告诉你WORD怎么搞

回答4:

string aline;
ifstream fin("xxoo.txt");
getline( fin, aline);
然后一行就在aline里了

回答5:

有openfile函数,打开txt直接用指针考就行