在 C++ 中多次尝试打开文本文件失败

Multiple failed attempts to open a text file in C++

过去一个小时我一直在研究如何在 C++ 中以编程方式显示文本文档。

下面是简单的main.cpp代码,我在其中创建了一个目录“Profiles”,并在里面创建了另一个目录“TestProfile”。在 Profiles/TestProfile 中,我创建了一个“TestFile”并将“测试数据”写入其中。

#include <iostream>
#include <fstream>
#include <sys/stat.h>

#include "Profile.hpp"
#include <stdlib.h>

using namespace std;
int main(int argc, const char * argv[]) {
    
    ofstream fs;
    
    mkdir("/Users/dario/Desktop/Profiles", S_IRWXU);
    mkdir("/Users/dario/Desktop/Profiles/TestProfile", S_IRWXU);
    fs.open("/Users/dario/Desktop/Profiles/TestProfile/TestFile");
      
    fs << "Test data\n";
    
   
    string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile";
    system(path.c_str());

    
    return 0;
}

第 30 行之前的所有内容都按预期工作。目录在那里,并且“TestFile”与写入的数据一起存在。

编译时没有出现错误,但是 ./a.out 拒绝了我的权限

darios-mbp:FMES dario$ g++ -std=c++2a main.cpp 
darios-mbp:FMES dario$ ./a.out 
sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied

我尝试了一些方法。

首先,我使用 ls -l 检查了文本文件的权限, 它返回 -rw-r--r--,所以我使用 chmod 755。之后,文件权限显示 -rwxr-xr-x。当运行使用相同的代码时,./a.out 返回没有拒绝权限,看起来它有效,但文本文件没有打开。

其次,在第一种方法无效后,我删除了目录和 ./a.out 以重新创建原始权限被拒绝的问题。

我和以前一样被拒绝权限,这次我尝试更改所有权或目录。

sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied
darios-mbp:FMES dario$ chown -R $USER  
/Users/dario/Desktop/Profiles/TestProfile/TestFile
darios-mbp:

该命令有效,但 运行尽管没有错误,但代码仍然没有执行任何操作。

我尝试了 chmod 755,但还是没有打开任何文件。

在以前尝试解决此问题时,在按照我刚才解释的方式更改所有权后,我什至在尝试 运行 文本文件的第一个单词作为命令时遇到错误

Line 1: Test: command not found

虽然我在写这篇文章时无法重新创建它。

也许我做的事情完全错了,但在写这篇文章之前,我尽可能多地在网上寻找解决方案 post。 None 其中似乎有效。也许我的情况在某种程度上是独一无二的,这里有人可以帮助我指明正确的方向。如果我的 post 在任何方面不符合标准,我提前道歉(如果是这样,请告诉我下次如何改进问题)。h

我正在 运行宁 xcode

上的代码

编辑

感谢@Codo 的回答,下面的编辑做了我想要的

string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile";
string cmd = "open -a TextEdit  ";
system(cmd.c_str());

我了解到您想使用合适的应用程序打开创建的文件。假设文件是​​ /dir/file.

要从命令行/终端打开文件,您需要 运行:

open /dir/file

或者,如果您想要特定的应用程序:

open -a TextEdit /dir/file

另见 The macOS open Command

如果你只是 运行:

/dir/file

你会执行文件。那可能不是你想要的。并且只有在文件满足某些条件(如执行权限)时才可能执行,并且在 shell 脚本的情况下,适当的 header.

在 C++ 中,system() 函数执行一个在命令行(在终端中)上有效的命令。

因此,要修复您的程序,请将带有 system() 的行更改为:

string cmd = "open -a TextEdit ";
cmd += path;
system(cmd.c_str());

对于你的下一个问题:将代码粘贴为文本,而不是图像:Why not upload images of code/errors when asking a question?