Чтение и запись файлов на C++: методы и примеры

Для записи и чтения файла на C++ можно использовать различные методы и библиотеки. Вот несколько часто используемых подходов:

  1. Использование библиотеки :

    #include <iostream>
    #include <fstream>
    int main() {
       std::ofstream file("example.txt"); // Open file for writing
       if (file.is_open()) {
           file << "This is some text." << std::endl; // Write data to the file
           file.close(); // Close the file
       } else {
           std::cout << "Failed to open the file." << std::endl;
       }
       std::ifstream readFile("example.txt"); // Open file for reading
       if (readFile.is_open()) {
           std::string line;
           while (getline(readFile, line)) {
               std::cout << line << std::endl; // Print each line of the file
           }
           readFile.close(); // Close the file
       } else {
           std::cout << "Failed to open the file." << std::endl;
       }
       return 0;
    }
  2. Использование библиотеки :

    #include <fstream>
    int main() {
       std::ofstream file("example.txt"); // Open file for writing
       if (file.is_open()) {
           file << "This is some text." << std::endl; // Write data to the file
           file.close(); // Close the file
       } else {
           std::cout << "Failed to open the file." << std::endl;
       }
       std::ifstream readFile("example.txt"); // Open file for reading
       if (readFile.is_open()) {
           std::string line;
           while (getline(readFile, line)) {
               std::cout << line << std::endl; // Print each line of the file
           }
           readFile.close(); // Close the file
       } else {
           std::cout << "Failed to open the file." << std::endl;
       }
       return 0;
    }
  3. Использование файловых операций в стиле C:

    #include <cstdio>
    int main() {
       FILE* file = fopen("example.txt", "w"); // Open file for writing
       if (file != nullptr) {
           fprintf(file, "This is some text.\n"); // Write data to the file
           fclose(file); // Close the file
       } else {
           printf("Failed to open the file.\n");
       }
       file = fopen("example.txt", "r"); // Open file for reading
       if (file != nullptr) {
           char line[256];
           while (fgets(line, sizeof(line), file) != nullptr) {
               printf("%s", line); // Print each line of the file
           }
           fclose(file); // Close the file
       } else {
           printf("Failed to open the file.\n");
       }
       return 0;
    }

Эти методы демонстрируют, как записывать и читать файл с помощью файловых операций C++ и C-стиля. Вы можете выбрать тот, который лучше всего соответствует вашим требованиям.