【问题标题】:Error when library receives the FILE pointer and read the file库收到 FILE 指针并读取文件时出错
【发布时间】:2012-09-25 13:57:24
【问题描述】:

该函数从文件中读取矩阵,并将其打印在屏幕上。但是库fscanf(fp, "%u", &elem);从fp读取文件时出现问题。

我把uint8_t elem改成uint8_t *elem就OK了。

我想知道为什么!程序将 FILE 指针传输到库时应注意什么。谢谢!

主要功能:

int main(int argc, char *argv[]){

    Matrix8g mat;
    FILE *fp;

    if((fp = fopen("mat.dat","r")) == NULL){
        printf("can't open the file");
    }
    //matrix with 24 rows and 11 cols
    mat.Make_from_file(fp, 24, 11);

    //print the matrix
    mat.Print();
    fclose(fp);
}

部分库文件(Make_from_file):

/* Set the matrix from a file */
int Matrix8g::Make_from_file(FILE *fp, int rows, int cols){
    int i, j;
    uint8_t elem;

    this->rr = rows;
    this->cc = cols;
    Resize_matrix();

    try{
        for(i = 0; i < rows; i++){
            for(j = 0; j < cols; j++){
                fscanf(fp, "%u", &elem);
                Set(i, j, elem);
            }
        }
    }catch(...){
        NOTE("Error when set the matrix from a file");
        return 0;
    }
    return 1;
}

【问题讨论】:

    标签: c++ file shared-libraries


    【解决方案1】:

    如果您查看此参考资料c reference

    您会看到 fscanf 需要对应写入提取日期的数据结构的引用。 fscanf 从给定的文件/流复制到给定的指针。它没有关于数据类型的信息。它使用格式字符串来解释输入中的字节。它类似于类型转换。 fscanf 无法知道需要哪种类型作为目标结构,但指针允许直接复制操作。

    【讨论】:

    • 是的,我误用了 fscanf,我将 uint8_t elem 更改为 unsigned int elem 现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多