fstream无法在raspberry pi上写/打开文件

问题描述 投票:0回答:1

我试图在raspberry pi 3 b +(来自'pi'用户)上运行cpp程序但是当我尝试用'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);

程序总是在那里失败并停止,因为没有创建文件(我没有得到致命的错误但是测试失败并且它输出'进程中的错误',这意味着没有创建文件)。 我正在使用以下命令进行编译(编译时没有问题):

g++ -std=c++0x nbFinder.cpp -o nbFinder

我已经在Xcode上尝试了我的程序,一切都很完美......

c++ raspberry-pi3 fstream
1个回答
0
投票

问题是你的道路。您必须放置文件,您只使用路径,如果路径不存在将抛出错误。在你的情况下你只使用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;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.