c++ - 如何从文本文件中读取文件名列表并在 C++ 中打开它们?

标签 c++ string file-io ifstream

我有一个存储在文本文件中的文件列表。我逐行读取文件并将它们存储在一个字符串数组中。文件列表如下所示:

04_02_1310.csv
04_03_1350.csv
04_04_0421.csv
04_05_0447.csv

等等。让我们调用我的字符串数组

filelist[i]

假设我正在尝试打开列表中的第一个文件:

inputFile.open(filelist[0].c_str()); // This cannot open file

无法打开文件。如果我将文件名放在引号中,一切正常:

inputFile.open("04_02_1310.csv"); // This works perfectly

如果我打印 filelist[i] 的内容,那么它也能正常工作:

cout << filelist[0] << endl; // This outputs 04_02_1310.csv on screen.

有人能告诉我上面的方法有什么问题吗?在过去的 2 天里,这让我发疯了,我将要手动输入所有内容以完成它(100 多个文件一个接一个)。

我也愿意接受任何其他方式来完成这个简单的任务。

谢谢!!!

编辑:如果您想查看它是如何实现的,我将添加代码的相关部分:

#include <cstdlib>
#include <iostream>
#include <time.h>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

//Declarations for I/O files
ifstream inputFile;

//Declare other variables (forgot to add these in my previous EDIT, sorry)
int number_of_files;
string line;
string *filelist = NULL;

//Open file list and count number of files
inputFile.clear();
inputFile.open("filelist.txt", ios::in);

//exit and prompt error message if file could not be opened
if (!inputFile){
    cerr << "File list could not be opened" << endl;
    exit(1);
}// end if

// count number of lines in the data file and prompt on screen
number_of_files = 0;

while (getline(inputFile, line))        
    number_of_files++;

cout << "Number of files to be analyzed: " << number_of_files << endl;

filelist = new string[number_of_files];
inputFile.close();

//Re-open file list and store filenames in a string array
inputFile.clear();
inputFile.open("filelist.txt", ios::in);

//exit and prompt error message if file could not be opened
if (!inputFile){
    cerr << "File list could not be opened" << endl;
    exit(1);
}// end if

// store filenames
i = 0;
while (getline(inputFile, line)){
    filelist[i] = line;
    //cout << filelist[i] << endl;
    i = i + 1;
}        

inputFile.close();

//open first file in the list, I deleted the loop to focus on the first element for now

inputFile.clear();
inputFile.open(filelist[0].c_str(), ios::in);

//exit and prompt error message if file could not be opened
if (!inputFile){
    cerr << "Data file could not be opened" << endl;
    exit(1);
}// end if

输出是:

Data file could not be opened

再次感谢!

最佳答案

该字符串中的文本文件中可能仍然存在 '\n' 字符(或 EOF,'\0' ),您应该尝试检查字符串是否“干净”。

关于c++ - 如何从文本文件中读取文件名列表并在 C++ 中打开它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474038/

相关文章:

c++ - C++中嵌套函数的设计模式

c++ - 连接 boost::mpl::string

string - 尝试异常替代方案以保护应用程序不崩溃

Java 自动装箱 ValueOf(String)

windows - 我如何与 xcopy 的速度相媲美?

c++ - 同时移动乒乓 Racket

c++ - 如何在文件系统的 Eclipse C++ 中添加 -lstdc++fs?

不使用函数比较两个字符串

c++ - 简单的 C++ 文件 I/O 问题

java - JTable从第二行读取文本文件