C语言从文件中读取数字

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>

using namespace std;

int index;

int* readFile(char* filename) {
    int* array;
    FILE* fp = fopen(filename, "r");
    if (!fp) {
        cout << "hello" << endl;
        return 0;
    }
    char* pBuf;
    int fLen;
    fseek(fp, 0, SEEK_END);
    fLen = ftell(fp);
    rewind(fp);

    array = (int*)malloc(fLen*4);
    pBuf = (char*)malloc(fLen + 1);
    index = 1;
    for (int i = 0; i < fLen; i++) {

        fscanf(fp, "%d", array + i);
        if (ftell(fp) == fLen) {
            break;
        }
        index++;
    }
    fclose(fp);
    array = (int *)realloc(array, index*4);
    
    cout << "indexΪ" << index << endl;
    return array;
}

int main()
{
    char wFilename[] = "weight.txt";
    char vFilename[] = "values.txt";

    int* weights = readFile(wFilename);
    int* values = readFile(vFilename);

    for (int t = 0; t < index; t++)
        cout << weights[t] << endl;
    cout << "_______________________________" << endl;
    for (int t = 0; t < index; t++)
        cout << values[t] << endl;
    free(weights);
    free(values);
}

 

posted @ 2020-11-24 22:45  giaoxiao  阅读(2214)  评论(0编辑  收藏  举报