如何传递一个字符串tostream ::打开的文件名 [英] How to pass a string to ofstream::open for the file name

查看:166
本文介绍了如何传递一个字符串tostream ::打开的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个C ++应用程序。我使用Visual C ++ 2010 Express。我试图写一个控制台程序,将线活着写在我的WD USB硬盘驱动器上的文件alive.txt每10秒,以防止驱动器旋转下来。我想让程序提示我驱动器盘符,然后使用它来告诉程序文件所在的位置。这个工程:

This is my first C++ app. I'm using Visual C++ 2010 Express. I'm trying to write a console program that will write the line "alive" to the file alive.txt on my WD USB hard drive every 10 seconds to prevent the drive from spinning down. I want the program to prompt me for the drive letter, and then use that to tell the program where the file is located. This works:

while (true)
{
Sleep(5000);
cout << "Past sleep";
ofstream AliveFile;
AliveFile.open ("j:\\alive.txt");
AliveFile << "alive" << endl;
AliveFile.close();
} 
return 0;

但是当我从控制台输入获取驱动器号并将路径保存到字符串并传递到AliveFile.open它不工作:

But when I get the drive letter from the console input and save the path to a string and pass that to AliveFile.open it doesn't work:

string DriveLetter;
cout << "What is the drive letter for the drive you want to keep awake?" << endl;
getline(cin, DriveLetter);
cin.clear();
string Path;
Path = "\"" + DriveLetter + ":\\alive.txt\"";
cout << Path << endl;

while (true)
{
Sleep(10000);
ofstream AliveFile;
AliveFile.open ( Path );
AliveFile << "alive" << endl;
AliveFile.close();
} 
return 0;

当我cout<路径,因此我不明白为什么AliveFile.open(Path)不工作。

The path comes out fine when i cout << Path so I do not understand why AliveFile.open(Path) does not work.

推荐答案

Path = "\"" + DriveLetter + ":\\alive.txt\"";  // Why adding \ before the root. 

尝试 -

Path = DriveLetter + ":\\alive.txt\"; 

这篇关于如何传递一个字符串tostream ::打开的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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