学习C++。将文件写入桌面。无处可寻
Learning C++. Writing File To Desktop. No Where to be Found
我正在学习 C++ 并尝试编写一个程序来在我的桌面上创建一个文本文件并写入它。
由于某种原因,我的桌面上找不到该文件。
这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("C:\Users\MyName\Desktop\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
我正在使用 Eclipse 构建和编译我的代码。这是它没有将文件写入我的桌面的原因吗?
对我来说很顺利...检查路径的 MyName 部分。它应该是您的用户名。我没有用 Eclipse,我用的是 Qt。
对我也有用。我在 ubuntu 上编译并 运行 这个。尝试从 Windows 中的命令行 运行 执行此操作,然后检查它是否有效。
只有一个准答案才能让 OP 走上调试自己代码的正确轨道。
文件流不会告诉你太多,除非你问他们。如果流无法打开,您仍然可以尝试从中读取。你不会得到任何东西,但你可以尝试。除非您询问,否则您甚至不会收到错误消息。 OP 没有询问,所以他们无法知道发生了什么或是否发生了什么。
Check to ensure the file is open
if myfile.is_open()
{
cout << "Opened the file, dude."<< endl;`
}
else
{
perror("Failed to open the file, man.");
}
并检查写入的结果
if(myfile << "Writing this to a file.\n")
{
cout << "Wrote to the file. Cool beans, man."<< endl;`
}
else
{
perror("Failed to write to the file, man.");
}
确保数据已写入。
The output of perror
should give you a hint of what went wrong and how to fix it.
我正在学习 C++ 并尝试编写一个程序来在我的桌面上创建一个文本文件并写入它。
由于某种原因,我的桌面上找不到该文件。
这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("C:\Users\MyName\Desktop\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
我正在使用 Eclipse 构建和编译我的代码。这是它没有将文件写入我的桌面的原因吗?
对我来说很顺利...检查路径的 MyName 部分。它应该是您的用户名。我没有用 Eclipse,我用的是 Qt。
对我也有用。我在 ubuntu 上编译并 运行 这个。尝试从 Windows 中的命令行 运行 执行此操作,然后检查它是否有效。
只有一个准答案才能让 OP 走上调试自己代码的正确轨道。
文件流不会告诉你太多,除非你问他们。如果流无法打开,您仍然可以尝试从中读取。你不会得到任何东西,但你可以尝试。除非您询问,否则您甚至不会收到错误消息。 OP 没有询问,所以他们无法知道发生了什么或是否发生了什么。
Check to ensure the file is open
if myfile.is_open()
{
cout << "Opened the file, dude."<< endl;`
}
else
{
perror("Failed to open the file, man.");
}
并检查写入的结果
if(myfile << "Writing this to a file.\n")
{
cout << "Wrote to the file. Cool beans, man."<< endl;`
}
else
{
perror("Failed to write to the file, man.");
}
确保数据已写入。
The output of perror
should give you a hint of what went wrong and how to fix it.