2015-04-26 32 views
-1

“您的任务是提示用户输入带有磁盘路径的文件名,如果该文件不存在于指定的位置,程序应该退出并显示一条合适的错误消息” 大家好,所以这是我有一个问题,我是能够得到用户输入一个文件名,这样的..让用户输入文件C++

1.   cout<< "enter the data file name you wish to open"; 
2.   cin >>file; 
3.   indata.open(file.c_str()); 
4.   outdata.open(file.c_str()); 

问题的第二部分是,如果文件不存在,该程序应该犯一个错误,我怎么会这样做,说我的文件名是txt.source,但用户输入lil.pol我怎么说它有一个错误,或者其他的话我怎么做使所需的文件名称唯一的电脑将接受?

回答

1

你可以做的是尝试打开该文件,如果无法通过std::cerr这样打开问题的消息:

std::ifstream indata(file.c_str()); 

if(!indata) // failed to open 
{ 
    std::cerr << "Error: could not open file: " << file << std::endl; 
    return 1; // error code 
} 

// use indata here (its open) 
1

编辑:

读/写数据:

void createfile() 
{ 
    ofstream file_handle("test.txt"); 
    if (!file_handle) 
     return; 

    //add record: 
    file_handle << "firstname1" << endl; 
    file_handle << "lastname1" << endl; 
    file_handle << "college1" << endl; 
    file_handle << "1001" << endl; 

    //add another record: 
    file_handle << "firstname2" << endl; 
    file_handle << "lastname2" << endl; 
    file_handle << "college2" << endl; 
    file_handle << "1002" << endl; 

    //remember each record is 4 lines, each field is single line 
    //this is the file format 
} 

int main() 
{ 
    createfile(); 

    ifstream fin("test.txt"); 
    if (!fin) 
    { 
     cout << "file not found" << endl; 
     return 0; 
    } 

    ofstream fout("out.txt");//note, it's a different name than input file 
    if (!fout) 
    { 
     cout << "cannot create new file" << endl; 
     return 0; 
    } 

    char buffer[1000]; 

    while (fin) 
    { 
     cout << "attempting to read record:\n"; 
     for (int i = 0; i < 4; i++) 
     { 
      fin.getline(buffer, 1000, '\n'); 
      if (!fin) break; 

      cout << buffer << endl;//write to screen 
      fout << buffer << endl;//write to file 

      if (i == 3) 
      { 
       //buffer is expected to be a number! 
       int number = atoi(buffer); 
       //multiply by random number 2, just testing 
       cout << number * 2 << endl; 
      } 
     } 
    } 

    return 0; 
} 

只要创建一个循环,并要求输入新的文件名是否错误。

int main() 
{ 
    ifstream indata; 
    string fname; 
    for (;;) 
    { 
     cout << "enter fname, zero to exit\n"; 
     cin >> fname; 
     if (fname == "0") 
      return 0; 
     indata.open(fname); 
     if (indata) 
      break;//file is valid and has been opened now 
     cout << "file not found, try again\n"; 
    } 

    return 0; 
} 
+0

所以这真的很有帮助,但它如何知道正确的文件名是什么,因为文件是一个字符串,我可以输入不同的名称,它会接受所有这些名称。我想要文件名是特定的 –

+0

这是一个非常简单的任务。 Galik的答案完全符合作业要求。如果文件名错误,则文件不在计算机上,打开操作失败。没有别的了。如果第一次出现错误,我会提出一个更加花哨的版本,要求重新进入,现在不要担心。下一步是为'outdata'创建一个文件。这次如果文件不在计算机上并不重要,程序将创建文件并准备好写入。只要确保为'outdata'输入了不同的文件名。 –

+0

所以我想最让我感到困惑的是,我有一个数据列表,名称院校和一个数字,我试图打开文件时输出,我不明白如何让他们输出。此外,当我有indata.open(文件)打开是红色的,不会工作 –