c - 程序不想读取文件

标签 c file struct

这是我的结构

   typedef struct {
        char mmsi[10];
        char name[20];
        double latitude;
        double longitude;
        int course;
        double speed;
    }Vessel;

这是我不想工作的功能

void searchByLatLong(double latitude, double longitude){
        FILE * file;
        struct dirent *drnt;
        DIR * dir = opendir("./text");
        char *path = (char *)malloc(19);
        Vessel *vessel = (Vessel *)malloc(sizeof(Vessel));

        while((drnt = readdir(dir)) != NULL) {
            if(strcmp(drnt->d_name,".") && strcmp(drnt->d_name,"..")) {

                strcpy(path,"text/");
                strcat(path,drnt->d_name);

                file=fopen(path, "r");
                fscanf(file," %s %[a-zA-Z0-9 ]19s %lf %lf %d %lf", &vessel->mmsi,&vessel->name,&vessel->latitude,&vessel->longitude,&vessel->course,&vessel->speed);

        //  if (mmsi+".txt" == drnt->d_name){
                    printf("%s\n%s\n%lf\n%lf\n%d\n%lf\n\n",vessel->mmsi,vessel->name,vessel->latitude,vessel->longitude,vessel->course,vessel->speed);
            //}


            fclose(file);
        }
        seekdir(dir, telldir(dir)); 

    //  if(this->mmsi == mmsi){
        //  printVessel();
    //  }

    }
    closedir(dir);
}

当我尝试加载 txt 文件时,它仅加载前两个字符串,然后加载内存中的一些垃圾。将数据加载到另一个变量不会改变任何东西;/ 这是应加载的示例 txt 文件:

3
RMS Titanic
22.222
33.333
4
5.9

最佳答案

问题出在您的格式字符串上。正确的格式字符串是:

" %s %19[a-zA-Z0-9 ] %lf %lf %d %lf"

字段宽度位于转换说明符之前。此外,[...] 序列是一个转换说明符,就像“s”一样。您看到的问题是 fscanf() 处理“3”,因为它与第一个 %s 匹配。然后它处理“RMS Titanic”,因为它匹配 %[a-zA-Z0-9 ] 但随后处理停止,因为输入中没有“19s”。此时剩余的参数未初始化。

您应该检查 fscanf() 的返回值。它会告诉您实际执行了多少次转换。

关于c - 程序不想读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9857035/

相关文章:

c - 在 C 中重命名 .dat 文件时权限被拒绝

ruby - 在 Ruby 中打开和保存 base64 编码的图像数据 URI

c# - 是否可以将固定字节数组转换为结构,以便在 C# 中进行双向更改?

c++ - 函数原型(prototype)和函数实现签名不一致地使用 const 可以吗?

c - 指向字符的指针 - 函数中的取消引用

c - 未触发 Atmel SAME70 USART 接收超时

c - iOS:将对象添加为属性监听器时,是否必须在释放对象之前将监听器设置为 "unregister"?

c++ - 在 C++ 中计算文本文件中的文本行数时出错

c - 结构 - 删除其中一个元素

C 结构、函数指针和头文件问题(不确定是哪个原因)