一、c读写文件
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void test1() {
FILE* fp = NULL;
fp = fopen("./test.txt", "w+");
fprintf(fp, "姓名:汪汪汪\n");
fputs("年龄:54\n", fp);
fclose(fp);
}
void test2() {
FILE* fp = NULL;
char buff[1024];
fp = fopen("./test.txt","r");
while (fgets(buff,1024,fp)!=NULL) {
printf("%s",buff);
}
fclose(fp);
}
int main() {
test2();
system("pause");
return 0;
}
二、c++读写文件
#include<iostream>
using namespace std;
#include<fstream>
void test01() {
ofstream ofs("./test.txt",ios::out|ios::trunc);
if (!ofs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
ofs << "姓名:哇哈哈" << endl;
ofs << "年龄:33" << endl;
ofs.close();
}
void test02() {
ifstream ifs("./test.txt",ios::in);
if (!ifs) {
cout << "文件打开失败" << endl;
return;
}
char buf[1024] = {0};
while (!ifs.eof()) {
ifs.getline(buf,sizeof(buf));
cout << buf << endl;
}
char c;
while ((c=ifs.get())!=EOF) {
cout << c;
}
ifs.close();
}
int main() {
test02();
system("pause");
return EXIT_SUCCESS;
}