C++ 文件读写

    1. #include <iostream>
    2. #include <fstream>
    3. void fileoperation(string filename){
    4. // 文件写入相关操作
    5. ofstream outFile;
    6. outFile.open("info.txt");
    7. outFile << fixed;
    8. outFile << "Make and model" << endl;
    9. outFile << "Year" << endl;
    10. outFile.close();
    11. // 文件读取操作
    12. ifstream inFile;
    13. inFile.open(filename);
    14. if (!inFile.is_open()){
    15. cout << "Could not open the file" << filename << endl;
    16. }
    17. string value;
    18. inFile >> value;
    19. if (inFile.eof())
    20. cout << "End of file reached;" << endl;
    21. else if (inFile.fail())
    22. cout << "Input terminated by data mismatch." << endl;
    23. else
    24. cout << "Input terminated for unknown reason." << endl;
    25. inFile.close();
    26. }
    27. int main() {
    28. fileoperation("info.txt");
    29. return 0;
    30. }