C语言文件读取并写入结构体,有关文件读写到结构体数组问题;

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

typedef struct IMG

{

char *name;

int weight;

int height;

}IMG;

这是我的结构体存的是 图片的名字 宽度 高度

void readWeightHeight(void)

{

FILE *fpbmp;

//FILE *fpm;

char filename[54];

char *bmpname =NULL;

long Handle;

int i = 0;

struct _finddata_t FileInfo;

if ((Handle = _findfirst("D:\\240\\*.bmp", &FileInfo)) == -1L)

printf("Cannot open file\n");

else

{

//printf("%s\n", FileInfo.name); 目录下的文件

do

{

sprintf(filename, "D:\\240\\%s", FileInfo.name);

fpbmp = fopen(filename, "r");

img[i].name = (char *)malloc(strlen(FileInfo.name)+1);//这里我不给结构体里面的指针分配内存 数据得不到内存(这样做是为了节省内存)

strcpy(img[i].name, FileInfo.name);

fseek(fpbmp, 18L, 0);

fread(&img[i].weight, 4, 1, fpbmp); //fread(&wight, 4, 1, fpbmp);

fseek(fpbmp, 22L, 0);

fread(&img[i].height, 4, 1, fpbmp); //fread(&hight, 4, 1, fpbmp);

//printf("name %s w:%d h:%d \n", img[i].name, img[i].weight, img[i].height);

i++;

} while (_findnext(Handle, &FileInfo) == 0);

_findclose(Handle);

}

}

到后面的读文件就会出问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中的文件结构主要包括文件指针和文件操作函数。下面是一个简单的介绍: 1. 文件指针: 在C语言中,使用文件指针来表示文件的位置和状态。文件指针是一个特殊的指针,用于指向文件的位置。常用的文件指针类型是`FILE`,它是通过`stdio.h`头文件定义的。 2. 文件操作函数: C语言提供了一系列的文件操作函数,用于打开、关闭、读取写入文件。常用的文件操作函数有: - `fopen()`:打开文件,返回一个指向文件的指针。 - `fclose()`:关闭文件。 - `fread()`:从文件读取数据。 - `fwrite()`:向文件写入数据。 - `fprintf()`:向文件中格式化输出数据。 - `fscanf()`:从文件中格式化读取数据。 下面是一个示例代码,演示了如何使用结构进行文件: ```c #include <stdio.h> // 定义一个结构 struct Student { char name[20]; int age; float score; }; int main() { struct Student stu; FILE *file; // 打开文件 file = fopen("student.txt", "w"); if (file == NULL) { printf("无法打开文件!\n"); return 1; } // 写入数据到文件 strcpy(stu.name, "张三"); stu.age = 18; stu.score = 90.5; fwrite(&stu, sizeof(struct Student), 1, file); // 关闭文件 fclose(file); // 打开文件 file = fopen("student.txt", "r"); if (file == NULL) { printf("无法打开文件!\n"); return 1; } // 从文件读取数据 fread(&stu, sizeof(struct Student), 1, file); printf("姓名:%s\n", stu.name); printf("年龄:%d\n", stu.age); printf("分数:%f\n", stu.score); // 关闭文件 fclose(file); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值