/*
文件名:IOClass.nut
路径:Dps_A/BaseClass/IOClass/IOClass.nut
创建日期:2024-09-19	14:13
文件用途:IO流类
*/
class IO extends Base_C_Object {
    _Fopen_Address = Module.getExportByName(null, "fopen");
    _Fgetc_Address = Module.getExportByName(null, "fgetc");
    _Fputc_Address = Module.getExportByName(null, "fputc");
    _Fgets_Address = Module.getExportByName(null, "fgets");
    _Fputs_Address = Module.getExportByName(null, "fputs");
    _Fread_Address = Module.getExportByName(null, "fread");
    _Fwrite_Address = Module.getExportByName(null, "fwrite");
    _Fclose_Address = Module.getExportByName(null, "fclose");
    _Fseek_Address = Module.getExportByName(null, "fseek");
    _Ftell_Address = Module.getExportByName(null, "ftell");
    _Rewind_Address = Module.getExportByName(null, "rewind");
    _Flush_Address = Module.getExportByName(null, "fflush");

    constructor(FileName, Modes) {
        local FileObj = Sq_CallFunc(_Fopen_Address, "pointer", ["pointer", "pointer"], Str_Ptr(FileName), Str_Ptr(Modes));
        if (FileObj) {
            base.constructor(FileObj);
        } else throw ("文件打开错误!  FileName: " + FileName);
    }

    //读取一行
    function ReadLine() {
        local Buffer = Memory.alloc(256);
        local RetFlag = Sq_CallFunc(_Fgets_Address, "pointer", ["pointer", "int", "pointer"], Buffer.C_Object, 256, this.C_Object);
        if (RetFlag)
            return Buffer.readUtf8String();
    }

    //读取一个
    function Read() {
        local RetFlag = Sq_CallFunc(_Fgetc_Address, "char", ["pointer"], this.C_Object);
        if (RetFlag) {
            return RetFlag;
        }
    }

    //读取指定大小
    function ReadBuffer(size) {
        local Buffer = Memory.alloc(size);
        local RetFlag = Sq_CallFunc(_Fread_Address, "int", ["pointer", "int", "int", "pointer"], Buffer.C_Object, 1, size, this.C_Object);
        if (RetFlag > 0) {
            return {
                count = RetFlag,
                str = Buffer.readUtf8String(RetFlag)
            };
        } else {
            return {
                count = 0,
                str = ""
            }
        }
    }


    //写入字符串
    function Write(Str) {
        local Buffer = Memory.allocUtf8String(Str);
        Sq_CallFunc(_Fputs_Address, "int", ["pointer", "pointer"], Buffer.C_Object, this.C_Object);
    }

    function Flush() {
        Sq_CallFunc(_Flush_Address, "pointer", ["pointer"], this.C_Object);
    }

    //关闭文件
    function Close() {
        Sq_CallFunc(_Fclose_Address, "pointer", ["pointer"], this.C_Object);
    }
}