Sfoglia il codice sorgente

feat: 添加getc函数

文件读取可以获得单个字符

link #7
SongZihuan 4 anni fa
parent
commit
a7b63892eb
1 ha cambiato i file con 30 aggiunte e 2 eliminazioni
  1. 30 2
      vmcore/ofunc/src/file_.c

+ 30 - 2
vmcore/ofunc/src/file_.c

@@ -96,7 +96,7 @@ ResultType file_read(O_FUNC){
 
     fseek(file->value->data.file.file, 0L, SEEK_CUR);  // 改变文件状态(什么都没做)
     if (ap[1].value != NULL) {  // 指定数量读取
-        size_t n;
+        vint n;
         if (ap[1].value->value->type == V_int)
             n = ap[1].value->value->data.int_.num;
         else if (ap[1].value->value->type == V_dou)
@@ -106,7 +106,7 @@ ResultType file_read(O_FUNC){
             return R_error;
         }
         tmp = memWide(n);
-        fgetws(tmp, n, file->value->data.file.file);
+        fgetws(tmp, (int)n + 1, file->value->data.file.file);
     } else {
         size_t n = 0;
         size_t step = 50;  // 一次性申请足够的内存, 不够则再增加50字节
@@ -231,6 +231,32 @@ ResultType file_flush(O_FUNC){
     return result->type;
 }
 
+ResultType file_getc(O_FUNC){
+    ArgumentParser ap[] = {{.type=only_value, .must=1, .long_arg=false},
+                           {.must=-1}};
+    LinkValue *file;
+    wint_t c;
+    setResultCore(result);
+    parserArgumentUnion(ap, arg, CNEXT_NT);
+    if (!CHECK_RESULT(result))
+        return result->type;
+    freeResult(result);
+
+    if ((file = ap[0].value)->value->type != V_file || file->value->data.file.file == NULL) {
+        setResultError(E_TypeException, INSTANCE_ERROR(file), LINEFILE, true, CNEXT_NT);
+        return R_error;
+    }
+
+    c = fgetwc(file->value->data.file.file);
+    if (c == WEOF)  // 若出现错误则返回EOF, 否则返回0
+        setResultError(E_ValueException, L"File EOF", LINEFILE, true, CNEXT_NT);
+    else {
+        wchar_t str[2] = {(wchar_t) c, NUL};
+        makeStringValue(str, LINEFILE, CNEXT_NT);
+    }
+    return result->type;
+}
+
 ResultType file_err_core(O_FUNC, int type){
     ArgumentParser ap[] = {{.type=only_value, .must=1, .long_arg=false},
                            {.must=-1}};
@@ -342,6 +368,7 @@ ResultType file_close(O_FUNC){
     }
 
     if (file->value->data.file.file != NULL && !file->value->data.file.is_std) {
+        fflush(file->value->data.file.file);
         fclose(file->value->data.file.file);
         file->value->data.file.file = NULL;
         file->value->data.file.is_std = true;
@@ -384,6 +411,7 @@ void registeredFile(R_FUNC){
                       {L"err", file_iserr, fp_obj, .var=nfv_notpush},
                       {L"clean", file_clean_err, fp_obj, .var=nfv_notpush},
                       {L"flush", file_flush, fp_obj, .var=nfv_notpush},
+                      {L"getc", file_getc, fp_obj, .var=nfv_notpush},
                       {inter->data.mag_func[M_ENTER], file_enter, fp_obj, .var=nfv_notpush},
                       {inter->data.mag_func[M_DEL], file_close, fp_obj, .var=nfv_notpush},
                       {inter->data.mag_func[M_EXIT], file_close, fp_obj, .var=nfv_notpush},