c++ TXT 读取,写入和清空

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;
}

在这里插入图片描述

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值