【发布时间】:2020-04-13 03:19:26
【问题描述】:
我是 C 编程新手,遇到了一些困难。我正在尝试重新编码以使用链表来存储您从文件中读取的结构,但我不明白如何保存文本行并将其添加到链表中。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include"Cars.h"
void write_to_file() {
FILE* file = NULL;
file = fopen("Cars.dat", "wb");
Car c = { "Toyota", "Civic", "black", 5, 50000 };
size_t ret = fwrite(&c, sizeof c, 1, file);
Car d = { "Toyota1", "Civic1", "Red", 2, 55000 };
ret = fwrite(&d, sizeof d, 1, file);
fclose(file);
}
void print_cars(Car *c, int count) {
FILE* f = fopen("output.txt", "w");
for (int i = 0; i < count; i++) {
fprintf(f, "%s %s %s %d %f\n", c[i].model, c[i].manufacturer, c[i].color, c[i].seatCapacity, c[i].price);
}
fclose(f);
}
void read_from_file() {
Car c;
size_t SIZE = sizeof c;
size_t ret = 1;
FILE* file = NULL;
file = fopen("Cars.dat", "rb");
int count = 0;
do{
ret = fread(&c, sizeof c, 1, file);
if (ret != 1)
break;
count++;
//printf("%s %s %s %d %f\n", c.model, c.manufacturer, c.color, c.seatCapacity, c.price);
}while(!feof(file));
fclose(file);
if (count == 0) {
printf("No cars in the file provided\n");
return;
}
file = fopen("Cars.dat", "rb");
Car* cars_array = NULL;
cars_array = (Car *)malloc(count * SIZE);
ret = fread(cars_array, SIZE*count, 1, file);
//printf("%d\n", ret);
print_cars(cars_array, count);
}
int main()
{
//write_to_file();
read_from_file();
return 0;
}
结构代码:
#ifndef Cars_h
#define Cars_h
typedef struct cars {
char manufacturer[35]; //toyota, honda
char model[35]; //camry, civic
char color[20]; //black, red
int seatCapacity; //4,5
float price; //20k, 25k
}
Car;
#endif
如果有人能给我一些关于我下一步需要做什么以使其工作的指示,我将不胜感激。谢谢你
【问题讨论】:
-
Can not read text file in C 应该会有所帮助...
-
fopen- 你为什么不检查返回值?
标签: c