fstream 无法 raspberry pi 上的 write/open 个文件
fstream fails to write/open files on raspberry pi
我正在尝试 运行 raspberry pi 3 b+ 上的 cpp 程序(来自 'pi' 用户)但是当我尝试用 'fstream' 库打开文件时不起作用。
我正在使用以下代码(来自 main):
std::ios::sync_with_stdio(false);
std::string path = "/NbData";
std::ofstream nbData(path);
if (!nbData) {
std::cout << "Error during process...";
return 0;
}
nbData.seekp(std::ios::beg);
程序总是在那里失败并停止,因为没有创建文件(我没有收到致命错误,但测试失败并输出 'Error during process',这意味着没有创建文件)。
我正在使用以下命令进行编译(编译时没有问题):
g++ -std=c++0x nbFinder.cpp -o nbFinder
我已经在 Xcode 上尝试了我的程序并且一切正常...
问题出在你的路径上。您必须放置文件,您只使用路径,如果路径不存在将引发错误。在你的情况下,你只是使用 std::string path = "/NbData";
,那是你的路径而不是你的文件。
为了能够打开您的文件,您需要确保您的路径存在。尝试使用下面的代码,他将检查路径是否存在,如果不创建,然后尝试打开您的文件。
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
std::ios::sync_with_stdio(false);
std::string path = "./test_dir/";
std::string file = "test.txt";
// Will check if thie file exist, if not will creat
struct stat info;
if (stat(path.c_str(), &info) != 0) {
std::cout << "cannot access " << path << std::endl;
system(("mkdir " + path).c_str());
} else if(info.st_mode & S_IFDIR) {
std::cout << "is a directory" << path << std::endl;
} else {
std::cout << "is no directory" << path << std::endl;
system(("mkdir " + path).c_str());
}
std::ofstream nbData(path + file);
if (!nbData) {
std::cout << "Error during process...";
return 0;
}
nbData.seekp(std::ios::beg);
return 0;
}
我正在尝试 运行 raspberry pi 3 b+ 上的 cpp 程序(来自 'pi' 用户)但是当我尝试用 'fstream' 库打开文件时不起作用。 我正在使用以下代码(来自 main):
std::ios::sync_with_stdio(false);
std::string path = "/NbData";
std::ofstream nbData(path);
if (!nbData) {
std::cout << "Error during process...";
return 0;
}
nbData.seekp(std::ios::beg);
程序总是在那里失败并停止,因为没有创建文件(我没有收到致命错误,但测试失败并输出 'Error during process',这意味着没有创建文件)。
我正在使用以下命令进行编译(编译时没有问题):
g++ -std=c++0x nbFinder.cpp -o nbFinder
我已经在 Xcode 上尝试了我的程序并且一切正常...
问题出在你的路径上。您必须放置文件,您只使用路径,如果路径不存在将引发错误。在你的情况下,你只是使用 std::string path = "/NbData";
,那是你的路径而不是你的文件。
为了能够打开您的文件,您需要确保您的路径存在。尝试使用下面的代码,他将检查路径是否存在,如果不创建,然后尝试打开您的文件。
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
std::ios::sync_with_stdio(false);
std::string path = "./test_dir/";
std::string file = "test.txt";
// Will check if thie file exist, if not will creat
struct stat info;
if (stat(path.c_str(), &info) != 0) {
std::cout << "cannot access " << path << std::endl;
system(("mkdir " + path).c_str());
} else if(info.st_mode & S_IFDIR) {
std::cout << "is a directory" << path << std::endl;
} else {
std::cout << "is no directory" << path << std::endl;
system(("mkdir " + path).c_str());
}
std::ofstream nbData(path + file);
if (!nbData) {
std::cout << "Error during process...";
return 0;
}
nbData.seekp(std::ios::beg);
return 0;
}