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 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:
ifstream
class to open a file. operator>>
or getline
to read data from the file. 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!