Zhonghui

每个不曾起舞的日子,都是对生命的辜负

User Tools

Site Tools


程序:cpp:文件操作

C++文件操作


需要用ifstream/ofstream,分别对应读写
头文件需要iostream/fstream
读取文本可以使用C风格的文件读取方式
退出之前记得close()

打开文件

void open(const char *filename, ios::openmode mode);

打开模式的参数:

  • ios::in:打开文件用于读取
  • ios::out:打开文件用于写入
  • ios::binary:以二进制形式打开(?)
  • ios::trunc:如果文件已经存在,其内容将在打开文件之前截断,即把长度设为0

设定文件指针位置

  • istream使用seekg
  • ostream使用seekp

参数分别指定偏移量和基准位置,基准位置可以使用以下

ios::beg//默认的,从流的开头开始定位
ios::cur//从流的当前位置开始定位
ios::end//从流的末尾开始定位

Info头文件

// Info.h
#ifndef INFO_STRUCT_H
#define INFO_STRUCT_H
 
#include<algorithm>
#include<cstring>
#include<cstdint>
#include<vector>
#include<cstdio>
 
typedef uint8_t Byte;
 
class Info
{
public:
    Info(int16_t info_id=0,int32_t x=0,int32_t y=0,int32_t z=0,float r=0.0f):
        info_id(info_id),x(x),y(y),z(z),r(r){}
    ~Info()=default;
 
protected:
    int16_t info_id;
    int32_t x,y,z;
    float r;
 
public:
    static void addBytes(std::vector<Byte> &Save,void* value,int size)
    {
        auto Target=new Byte[size];
        memcpy(Target,value,size);
 
        for(int i=0;i<size;i+=1) Save.push_back(Target[i]);
 
        delete[] Target;
    }
 
public:
    void toBytes(std::vector<Byte> &Save,bool clear=false)
    {
        if(clear) Save.clear();
 
        addBytes(Save,reinterpret_cast<void*>(&info_id),2);
        addBytes(Save,reinterpret_cast<void*>(&x),4);
        addBytes(Save,reinterpret_cast<void*>(&y),4);
        addBytes(Save,reinterpret_cast<void*>(&z),4);
        addBytes(Save,reinterpret_cast<void*>(&r),4);
    }
 
    void fromBytes(const std::vector<Byte> &Saved,int startIndex)
    {
        if(startIndex+18>Saved.size())
        {
            puts("Read EOF");
            return;
        }
 
        //Is not Add X Bytes!!!
        //Is Add X Size of Element
        auto Index=Saved.data()+startIndex;
 
        memcpy(&info_id,Index,   2);
        memcpy(&x,      Index+2, 4);
        memcpy(&y,      Index+6, 4);
        memcpy(&z,      Index+10,4);
        memcpy(&r,      Index+14,4);
    }
 
    void print() const
    {
        printf("[%02d]: %d %d %d %f\n",info_id,x,y,z,r);
    }
};
 
#endif

Save源文件

// Save.cpp
#include<iostream>
#include<fstream>
 
#include"Info.h"
 
int main()
{
    using std::ios;
 
    std::vector<Info> infos;
 
    //Data
    infos.push_back(Info(1,-1,0,1,3.14f));
    infos.push_back(Info(2,-2,0,2,1.00f));
    infos.push_back(Info(3,-5,0,9,2.73f));
    infos.push_back(Info(4,-5,0,9,2.73f));
    infos.push_back(Info(5,-5,0,9,2.73f));
 
    //Open file
    std::ofstream save_info;
    save_info.open("some_thing.info",ios::binary|ios::out|ios::trunc);
 
    //Save Count
    uint16_t InfoCount=infos.size();
    save_info.write(reinterpret_cast<char*>(&InfoCount),2);
    printf("Saving %d info(s)\n",InfoCount);
 
    //Save Data
    for(uint16_t i=0;i<InfoCount;i+=1)
    {
        std::vector<Byte> info_byte;
        infos[i].toBytes(info_byte,true);
 
        //Number of Bytes
        save_info.write(reinterpret_cast<char*>(info_byte.data()),18);
        printf("Save a Info: ");
        infos[i].print();
    }
 
    //Close File
    save_info.close();
 
    return 0;
}

Read源文件

// Read.cpp
#include<iostream>
#include<fstream>
 
#include"Info.h"
 
int main()
{
    using std::ios;
 
    //Open File
    std::ifstream read_info;
    read_info.open("some_thing.info",ios::binary|ios::in);
    read_info.seekg(0,ios::beg);
 
    //Read Count
    uint16_t InfoCount=0;
    read_info.read(reinterpret_cast<char*>(&InfoCount),2);
    printf("Reading %d info(s)\n",InfoCount);
 
    //Read Each Record
    for(int i=1;i<=InfoCount;i+=1)
    {
        Info info;
        std::vector<Byte> info_byte;
 
        info_byte.resize(18);
        read_info.read(reinterpret_cast<char*>(info_byte.data()),18);
 
        info.fromBytes(info_byte,0);
        printf("Read a info: ");
        info.print();
    }
 
    //Close File
    read_info.close();
 
    return 0;
}

读取文本

#include<cstdio>
 
int main()
{
    FILE* WriteFile=fopen("Word.txt","w");
    if(!WriteFile) return 1;
 
    fprintf(WriteFile,"Hello World");
 
    fclose(WriteFile);
 
    puts("Write Done");
 
    FILE* ReadFile=fopen("Word.txt","r");
    if(!ReadFile) return 1;
 
    char ReadBuffer[1024];
    while(EOF!=fscanf(ReadFile,"%s",ReadBuffer))
    {
        printf(">> %s\n",ReadBuffer);
    }
    fclose(ReadFile);
 
    return 0;
}
/var/www/DokuWikiStick/dokuwiki/data/pages/程序/cpp/文件操作.txt · Last modified: 2022/03/24 12:22 (external edit)