本文介绍了如何在c ++中将读取文件的相对地址用于字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我非常尝试从相对地址使用但我不知道问题在哪里?
看下面的代码
I tried very much for use from relative address but I don't know problem is where?
look below code
string FileName;
cin >> FileName;
ifstream t(FileName);
string str;
t.seekg(0, ios::end);
str.reserve(t.tellg());
t.seekg(0, ios::beg);// message error
str.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
但我无法读取文件到字符串,我再试一次。
看下面代码
but I can't read file to string and I try again.
look below code
string FileName;
cin >> FileName;
ifstream ifs(FileName);
string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
// str is empty
但绝对地址我没有问题。
以下代码显示绝对地址
but in absolute address I haven't problem.
below code show absolute address
string FileName;
cin >> FileName;
FileName = "C:\\Users\\kaveh\\Documents\\Visual Studio 2013\\Projects\\DCEL\\Debug\\" +FileName;
ifstream t(FileName);
string str;
t.seekg(0, ios::end);
str.reserve(t.tellg());
t.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
文件和程序在同一个目录中
file and program are in one same directory
推荐答案
string FileName;
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
string directory = buffer;
unsigned int index;
for (index = directory.length()-1; index > 0; index--)
{
if (directory[index] == '\\')
{
index++;
break;
}
}
directory.erase(directory.begin() + index, directory.begin() + directory.length());
cin >> FileName;
FileName = directory + FileName;
ifstream t(FileName);
string str;
t.seekg(0, ios::end);
str.reserve(t.tellg());
t.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
</char></char>
这篇关于如何在c ++中将读取文件的相对地址用于字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!