C++ 编译器找不到文件

标签 c++ file io

我已经为此工作了很长一段时间,但似乎无法理解为什么文件 sample_uc_students.txt 和 sample_smc_grads.txt 没有被读取。它们是我放入文档文件夹但打不开的预制文档。

Student* readStudentsFromFile(string filename, int num) {
ifstream studentsStream;
studentsStream.open(filename.c_str());
if (!studentsStream.is_open()) {
    cerr << "Couldn't open the file " << filename << endl;
    return NULL;
}
// create a new array of students with size 'num'
Student* students = new Student[num];
string name, school, sid;
int id;
// read student records from file
for (int i = 0; i < num; i++) {
    getline(studentsStream, name, ',');
    getline(studentsStream, sid, ',');
    getline(studentsStream, school);
    istringstream idConv(sid);
    idConv >> id;
    // create a student object from the record and store it in the array
    students[i] = Student(id, name, school);
}
studentsStream.close();
return students;
}

int main() {

const int SIZE = 10;
const int SMC_SIZE = 5;
const int SMC_UC_GRADS_SIZE = 2;
Student* uc = readStudentsFromFile("sample_uc_students.txt", UC_SIZE);
Student* smc = readStudentsFromFile("sample_smc_grads.txt", SMC_SIZE);

\Time it will take
time_t start, end;

time(&start);
Student* common1 = findCommonStudents1(uc, UC_SIZE, smc, SMC_SIZE,
                                       SMC_UC_GRADS_SIZE);
time(&end);
cout << "Using linear search it took " << difftime(end, start) << " seconds."
<< endl;

/*
 * library sort function to sort an array: sort(arr, arr+size)
 * Note that values must be comparable with the < operator
 */ 


sort(common1, common1 + SMC_UC_GRADS_SIZE);
writeStudentsToFile(common1, SMC_UC_GRADS_SIZE, "smc_grads_at_uc_1.txt");

time(&start);
Student* common2 = findCommonStudents2(uc, UC_SIZE, smc, SMC_SIZE,
                                       SMC_UC_GRADS_SIZE);
time(&end);
cout << "Using binary search it took " << difftime(end, start)
<< " seconds." << endl;

sort(common2, common2 + SMC_UC_GRADS_SIZE);
writeStudentsToFile(common2, SMC_UC_GRADS_SIZE, "smc_grads_at_uc_2.txt");

delete[] smc;
delete[] uc;
delete[] common1;
delete[] common2;
return 0;

}

关于如何打开它们的任何建议,或者我应该尝试通过路径打开它们?

最佳答案

当您使用时:

Student* uc = readStudentsFromFile("sample_uc_students.txt", UC_SIZE);

程序希望文件“sample_uc_students.txt”位于程序运行的同一目录中。它不会在您的文档文件夹中查找文件。

您的选择:

  1. 将文件复制到程序运行的目录。
  2. 使用文件的绝对路径,而不是只使用文件名。

关于C++ 编译器找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899753/

相关文章:

c++ - 为什么 usernametwo 总是被跳过?

Java createNewFile 无法在本地网络上工作

java.io.File 与 java.nio.Files 哪个是新代码中的首选?

java - 通过 Java NIO API 传输文件

c++ - BeagleBone Black 从用户空间获取中断

c++ - {𝑥^(0),𝑥(1),……,𝑥(𝑦)}的偏群之和

java - 通过 Java 将文本插入现有文件

C++ 复制文件。数据不足

java - 如何获得将二维数组打印到java中的两个文件中的函数?

C++ 测试 lambda 函数