Home  >  Article  >  Backend Development  >  How to import file contents into the program in c++

How to import file contents into the program in c++

下次还敢
下次还敢Original
2024-04-22 17:45:531114browse

There are two common ways to read data from a file in C: open the file using a file stream, read the data in, and close the file. Use the C standard library functions fopen, fread, fwrite, and fclose for file processing.

How to import file contents into the program in c++

How to read data from a file in C

In C, read data from a file There are two common methods:

1. Use file stream

File stream is a way of processing files in C. It provides a set of functions to read Write file. To read a file using a file stream, you need to perform the following steps:

  • Open a file: Use the ifstream class to open a file.
  • Read data: Use functions such as operator>> or getline to read data from the file.
  • Close the file: Use the close function to close the file.

Sample code:

<code class="cpp">#include <fstream>
#include <iostream>

int main() {
  std::ifstream file("data.txt");
  if (file.is_open()) {
    std::string line;
    while (std::getline(file, line)) {
      std::cout << line << std::endl;
    }
    file.close();
  }
  return 0;
}</code>

2. Using C standard library functions

The C standard library also provides a set of functions to process files :

  • fopen: Open the file.
  • fread: Read data from the file.
  • fwrite: Write data to the file.
  • fclose: Close the file.

Sample code:

<code class="cpp">#include <stdio.h>

int main() {
  FILE *file = fopen("data.txt", "r");
  if (file != NULL) {
    char buffer[1024];
    while (fread(buffer, sizeof(char), 1024, file) != 0) {
      printf("%s", buffer);
    }
    fclose(file);
  }
  return 0;
}</code>

The above is the detailed content of How to import file contents into the program in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to export c++ programNext article:How to export c++ program