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);
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM