c++ TXT 读取,写入和清空
#include <iostream>
#include <fstream>
#include <string.h>
#define M 200
using namespace std;
void writefile(string s)
{
ofstream fout(s, ios::app | ios::out);
char a[M];
int i = 0;
printf("输入字符:\n");
while (1)
{
char x;
scanf("%c", &x);
if (x == '>')
break;
else
a[i++] = x;
}
for (int j = 0; i > 0; i--)
{
fout << a[j++];
}
fout.close();
cout << "[operation succeeded]" << endl;
}
char *readfile(string s, char *a)
{
ifstream fin;
fin.open(s);
int i = 0;
while (fin.getline(a + i, M - 1))
{
i = strlen(a);
if (i)
a[i++] = '\n';
}
if (!i)
printf("[empty txt]\n");
fin.close();
return a;
}
void clearfile(string s)
{
FILE *pfd = NULL;
const char *p = s.c_str();
pfd = fopen(p, "w+");
if (pfd)
{
cout << "[clear succeeded]" << endl;
fclose(pfd);
}
}
int main()
{
string filename = "D:\\top\\text.txt";
char a[M];
int k;
printf("1.写 2.读 3.清空 4.退出\n");
do
{
scanf("%d", &k);
switch (k)
{
case 1:
writefile(filename);
break;
case 2:
cout << readfile(filename, a);
break;
case 3:
clearfile(filename);
break;
case 4:
break;
default:
printf("输入错误,重新输入\n");
break;
}
} while (k != 4);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/04d219bfa8eff2cea41b4d3e28bd8cff.png)