c風格讀寫檔案

weixin_34050427發表於2018-12-20
#include<iostream>
using namespace std;

/*
 */
void write(int *p, char const *path) {
    FILE *fp;
    if ((fp = fopen(path, "wb")) == NULL) {
        cout << "檔案開啟失敗!" << endl;
        exit(0);
    }
    
    if (fwrite(p, sizeof(int), 1, fp) != 1) {
        cout << "寫入失敗!" << endl;
    }
    fclose(fp);
}

int read(char const *path) {
    int a;
    FILE *fp;
    if ((fp = fopen(path, "r")) == NULL) {
        cout << "檔案開啟失敗!" << endl;
    }
    
    fseek(fp, 0L, SEEK_END);
    long len = ftell(fp);
    rewind(fp);
    
    if (fread(&a, 1, len, fp) != len) {
        cout << "讀取失敗" << endl;
    }
    fclose(fp);
    
    return a;
}

int main() {
    //char *name = "I'm a student.李雷";
    char const *path = "./test.txt";
    int b = 224433;
    write(&b, path);
    
    //char *content;
    int a;
    a = read(path);
    
    cout << "content:" << a << endl;
    
    return 0;
}

相關文章