C++使用用户输入打开不同目录中的文件

发布于 2024-12-19 04:08:55 字数 2045 浏览 5 评论 0原文

我一直在编写一个 C++ 程序,该程序最终会从文本文件中删除某些不需要的格式。不幸的是,我距离这个目标还很远。

我当前的问题是我似乎无法打开位于给定(用户输入)目录中的文本文件。这是我到目前为止所处的位置,去掉了最不需要的部分:

//header, main function, bulk

//variable definitions
FILE * pFile;
//char filePathBuffer [512];  --unused, from older attempts
string currentLine = "", command = "", commandList = "ct", filePath = "defaultPath";
int quotePos = 0, slashPos = 0, bufferLength = 0;
bool contQuote = true, contSlash = true;

cout << "> ";
getline(cin, command);

//various exit commands
while(command != "q" && command != "quit" && command != "exit") {

    //check for valid commands stored in a string
    //--definitely not the best way to do it, but it's functional

    if(commandList.find(command) == commandList.npos) {
        puts("\nPlease enter a valid command.\n");
    }
    else if(command == "t") {
        puts("\nPlease enter the file path:\n");
        cout << "> ";
        getline(cin, filePath);

        //rip all quotes out of the entered file path
        while(contQuote == true) {
            quotePos = filePath.find("\"");

            if(quotePos == filePath.npos)
                contQuote = false;
            else
                filePath.erase(quotePos, 1);
        }

        pFile = fopen(filePath.c_str(), "r+");

        //I've also tried doing countless variations directly in the code,
        //as opposed to using user-input. No luck.
        //pFile = fopen("C:\\test.txt", "r+");

        if(pFile!=NULL) {
            cout << "\nFile opened!" << endl << endl;
            fclose (pFile);
        }
        else
            cerr << "\nFile failed to open!\n\n";

    }

    //reset variables to default values
    quotePos = -1;
    slashPos = -1;
    contQuote = true;
    contSlash = true;

    cout << "> ";
    getline(cin, command);
}

我实际上不确定输入字符串是否应该有引号 - 我无法让它们以任何方式工作。我还尝试执行 filePath.find('\\') 来查找反斜杠(这样我就可以在 filePath 中添加第二个反斜杠以进行正确的解析),但最终没有运气。

你们知道我该如何解决这种情况吗?

谢谢!

I've been writing a C++ program that will eventually remove certain undesired formatting from text files. Unfortunately, I'm still far from reaching this goal.

My current issue is my seeming inability to open text files that are located in a given (user-inputted) directory. Here is where I'm at so far, stripped of most unneeded bulk:

//header, main function, bulk

//variable definitions
FILE * pFile;
//char filePathBuffer [512];  --unused, from older attempts
string currentLine = "", command = "", commandList = "ct", filePath = "defaultPath";
int quotePos = 0, slashPos = 0, bufferLength = 0;
bool contQuote = true, contSlash = true;

cout << "> ";
getline(cin, command);

//various exit commands
while(command != "q" && command != "quit" && command != "exit") {

    //check for valid commands stored in a string
    //--definitely not the best way to do it, but it's functional

    if(commandList.find(command) == commandList.npos) {
        puts("\nPlease enter a valid command.\n");
    }
    else if(command == "t") {
        puts("\nPlease enter the file path:\n");
        cout << "> ";
        getline(cin, filePath);

        //rip all quotes out of the entered file path
        while(contQuote == true) {
            quotePos = filePath.find("\"");

            if(quotePos == filePath.npos)
                contQuote = false;
            else
                filePath.erase(quotePos, 1);
        }

        pFile = fopen(filePath.c_str(), "r+");

        //I've also tried doing countless variations directly in the code,
        //as opposed to using user-input. No luck.
        //pFile = fopen("C:\\test.txt", "r+");

        if(pFile!=NULL) {
            cout << "\nFile opened!" << endl << endl;
            fclose (pFile);
        }
        else
            cerr << "\nFile failed to open!\n\n";

    }

    //reset variables to default values
    quotePos = -1;
    slashPos = -1;
    contQuote = true;
    contSlash = true;

    cout << "> ";
    getline(cin, command);
}

I'm not actually sure whether the input string should have quotes or not - I couldn't get them to work either way. I also tried to do a filePath.find('\\') to find backslashes (so that I could then add a second backslash into the filePath for proper parsing), but had no luck in the end.

Do you guys have any idea how I can remedy this situation?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只有影子陪我不离不弃 2024-12-26 04:08:56

我建议你在调用 fopen 时看一下 filePath 包含什么。然后您将能够看到出了什么问题。

两种方法:

  1. 在调用 fopen 之前打印出值

  2. 使用调试器,在 fopen 调用上放置断点并检查文件路径的内容

I suggest you take a look at what filePath contains when you call fopen. Then you will be able to see what is going wrong.

Two approaches:

  1. Print out the value just before you call fopen

  2. Use debugger, place breakpoint on fopen call and inspect content of filepath

夜司空 2024-12-26 04:08:56

\\ 来看,我猜你是在 Windows 上。

尝试此函数:

#include <windows.h>
bool fileExist(const std::string& fileName_in)
{ 
  DWORD ftyp = GetFileAttributesA(fileName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;
  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return false;   // this is a directory
  return true;      // this is a normal file
}

尝试使用此函数输入字符串。如果它返回 false 告诉你的用户他是盲人:)

I guess you are on windows judging from \\.

Try this function :

#include <windows.h>
bool fileExist(const std::string& fileName_in)
{ 
  DWORD ftyp = GetFileAttributesA(fileName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;
  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return false;   // this is a directory
  return true;      // this is a normal file
}

Try the input string with this function. If it returns false tell your user that he is blind :)

假扮的天使 2024-12-26 04:08:56

看起来像是权限问题。您在其他子目录中尝试过吗?我添加了一些代码来检查 fopen() 返回时的 errno 值 - 请注意下面的“权限被拒绝”:

> t

Please enter the file path:

> .\test.cpp

File opened!

> t

Please enter the file path:

> c:\setup.log

File failed to open with error: Permission denied

> t

Please enter the file path:

> c:\cygwin\cygwin.bat

File opened!

>

Looks like a permission issue. Have you tried in other subdirectories? I added a bit of code to check the errno value when fopen() returns - note the "Permission Denied" below:

> t

Please enter the file path:

> .\test.cpp

File opened!

> t

Please enter the file path:

> c:\setup.log

File failed to open with error: Permission denied

> t

Please enter the file path:

> c:\cygwin\cygwin.bat

File opened!

>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文