扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

C++鏂囦欢鍑芥暟鏈夊摢浜涘強鎬庝箞浣跨敤

扬州沐宇科技
2023-08-17 23:15:01
c++

C++涓殑鏂囦欢鎿嶄綔鍑芥暟涓昏鍖呮嫭浠ヤ笅鍑犱釜锛?/p>

  1. std::ifstream锛氱敤浜庝粠鏂囦欢涓鍙栨暟鎹€?/li>

浣跨敤鏂规硶绀轰緥锛?/p>

#include <fstream>
#include <iostream>
int main() {
std::ifstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::ofstream锛氱敤浜庡悜鏂囦欢涓啓鍏ユ暟鎹€?/li>

浣跨敤鏂规硶绀轰緥锛?/p>

#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, World!" << std::endl;
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::fstream锛氱敤浜庢棦鑳借鍙栧張鑳藉啓鍏ユ枃浠躲€?/li>

浣跨敤鏂规硶绀轰緥锛?/p>

#include <fstream>
#include <iostream>
int main() {
std::fstream file("example.txt");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.clear();  // 娓呴櫎閿欒鏍囧織
file.seekg(0, std::ios::end);  // 瀹氫綅鍒版枃浠舵湯灏?/span>
file << "Hello, World!" << std::endl;
file.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
  1. std::remove锛氱敤浜庡垹闄ゆ枃浠躲€?/li>

浣跨敤鏂规硶绀轰緥锛?/p>

#include <iostream>
int main() {
if (std::remove("example.txt") != 0) {
std::cout << "Unable to delete file" << std::endl;
}
return 0;
}

浠ヤ笂鏄竴浜涘父鐢ㄧ殑鏂囦欢鎿嶄綔鍑芥暟鐨勭畝鍗曠ず渚嬶紝鏇磋缁嗙殑浣跨敤鏂规硶鍙互鍙傝€冪浉鍏虫枃妗f垨鏁欑▼銆?/p>

扫码添加客服微信