12.20

fgetc(指针名);

fgetc(数组名,数组长度,指针名);读操作

fputc(数组名,指针名);写操作

fscanf(指文件指针名,后面都跟printf一样)

fprintf(指文件指针名,后面都跟printf一样)

fread(从哪写{数组首地址&arr【1】},写的大小{sizeof(struct MM)},写几次,文件指针名}如果文件流已经到达文件末尾,feof函数返回非零值(通常是1)。否则,它返回零。

readfile(文件指针,变量,结构体指针)

写入文件:

#include <iostream>
using namespace std;
#include<stdio.h>
#include<string>
int r = 0;
void write(const char*filename)

{
    FILE *q = fopen(filename, "w");
    
    char arr[1024] = { 0 };
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
        fputc(arr[i], q);
    }

    fclose(q);
}
int main()
{
    void write(const char*filename);
    
    write("love");
    system("pause");
    return 0;
}

2.读文件

#include <iostream>
using namespace std;
#include<stdio.h>
#include<string>

void read(const char*filename)

{
    int r = 0;
    FILE *q = fopen(filename, "r");
    
    char arr[1024] = { 0 };
    int jie = fgetc(q);
    while(jie!=EOF)
    {
        arr[r++] = jie;
        jie = fgetc(q);
    }

要用一个int 型变量jie代表 FILE *q指向的变量
    arr[r] = '\0';

记得最后一个要用‘\0’占位
    printf("%s", arr);

用string字符串输出


    fclose(q);
}
int main()
{
    void read(const char*filename);
    
    read("love");
    system("pause");
    return 0;
}

#include <iostream>  
#include <cstdio>  
#include <string>  
using namespace std;
struct shuaige
{
    std::string m_name;
    int m_age;
    int m_jblength;
};

void readfile(const char* filename, int geshu, shuaige* gegemen)
{
    FILE *q = fopen(filename, "w"); // 使用 "a" 模式打开文件  

    for (int i = 0; i < geshu; i++)
    {
        fprintf(q, "哥哥的名字:%s\t哥哥的年龄:%d\t哥哥的长度:%d\t", gegemen[i].m_name.c_str(), gegemen[i].m_age, gegemen[i].m_jblength);
    }转化为c风格字符串再打印

    fclose(q);
}

int main()
{
    shuaige arr[3] = { {"肖战哥哥",30,20}, {"周楷哥哥",19,14}, {"一博哥哥",31,22} };
    shuaige* r = arr;
    readfile("love", 3, r);  

system("pause"); 
    return 0;
}

如果文件流已经到达文件末尾,feof函数返回非零值(通常是1)。否则,它返回零。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值