C语言
#include <stdio.h>
int main() {
// 写文本文件
FILE* textFile = fopen("example.txt", "w");
if (textFile) {
fprintf(textFile, "Hello, this is a text file!\n");
fclose(textFile);
} else {
perror("Failed to open text file for writing");
}
// 读文本文件
textFile = fopen("example.txt", "r");
if (textFile) {
char buffer[100];
while (fgets(buffer, sizeof(buffer), textFile)) {
printf("%s", buffer);
}
fclose(textFile);
} else {
perror("Failed to open text file for reading");
}
// 写二进制文件
FILE* binaryFile = fopen("example.bin", "wb");
if (binaryFile) {
int data = 42;
fwrite(&data, sizeof(data), 1, binaryFile);
fclose(binaryFile);
} else {
perror("Failed to open binary file for writing");
}
// 读二进制文件
binaryFile = fopen("example.bin", "rb");
if (binaryFile) {
int data;
fread(&data, sizeof(data), 1, binaryFile);
printf("Read from binary file: %d\n", data);
fclose(binaryFile);
} else {
perror("Failed to open binary file for reading");
}
return 0;
}
C++
#include <iostream>
#include <fstream>
int main() {
// 写文本文件
std::ofstream textOutFile("example.txt");
if (textOutFile.is_open()) {
textOutFile << "Hello, this is a text file!\n";
textOutFile.close();
} else {
std::cerr << "Failed to open text file for writing\n";
}
// 读文本文件
std::ifstream textInFile("example.txt");
if (textInFile.is_open()) {
std::string line;
while (std::getline(textInFile, line)) {
std::cout << line << '\n';
}
textInFile.close();
} else {
std::cerr << "Failed to open text file for reading\n";
}
// 写二进制文件
std::ofstream binaryOutFile("example.bin", std::ios::binary);
if (binaryOutFile.is_open()) {
int data = 42;
binaryOutFile.write(reinterpret_cast<char*>(&data), sizeof(data));
binaryOutFile.close();
} else {
std::cerr << "Failed to open binary file for writing\n";
}
// 读二进制文件
std::ifstream binaryInFile("example.bin", std::ios::binary);
if (binaryInFile.is_open()) {
int data;
binaryInFile.read(reinterpret_cast<char*>(&data), sizeof(data));
std::cout << "Read from binary file: " << data << '\n';
binaryInFile.close();
} else {
std::cerr << "Failed to open binary file for reading\n";
}
return 0;
}