有没有办法一次性导入文本文件中的所有字符串? 我想从文本文件中导入所有价格,其中字符串由产品名称和价格本身在同一行中组成。示例:" Wood 5 \ nIron 10 \ n"。 我的职责是:
fp = fopen("prices.txt", "r");
fgets(chestplate, 80, (FILE*)fp);
fgets(helmet, 80, (FILE*)fp);
fclose(fp);
这使得var胸甲" Wood 5" var head" Iron 10",有没有办法循环这个功能所以我不需要一次导入一个?
答案 0 :(得分:1)
这是循环文件中所有行的方法。
char string[80];
while (fgets(string, 80, fp)) {
// Do something to string
}
答案 1 :(得分:1)
继续由@Fjotten开始的示例,这里有一些(未经测试,未编译的)代码可以读取单个"价格"。您将要遍历所有这些,然后将它们存储在您需要的任何数据结构中 - 可能是某种对象数组。
#define ERROR_MSG(...) ... whatever you want ...
#define STREQUAL(a,b) (0 == stricmp(a,b))
typedef struct {
int wood;
int iron;
int bronze;
int diamond;
} PRICE;
PRICE * get_price(FILE * fp) {
char line[80];
int line_no = 0;
char units[80];
int qty;
PRICE * price;
while (fgets(line, sizeof(line), fp)) {
// Skip over blank lines, comments?
if (sscanf(line, " %s %d", units, &qty) != 2) {
ERROR_MSG("sscanf error reading prices, at line %d", line_no);
continue; // break? exit?
}
if ((price = calloc(1, sizeof(PRICE)) == NULL) {
ERROR_MSG("calloc failure reading prices, at line %d", line_no);
exit(1);
}
if (STREQUAL("wood", units)) {
price->wood = qty;
}
else if (STREQUAL("iron", units)) {
price->iron = qty;
}
// else if ...
else {
ERROR_MSG("Unrecognized currency '%s' reading prices, at line %d",
units, line_no);
continue;
}
return price;
}
}
typedef enum {
CHESTPLATE,
HELMET,
NUM_TREASURES
} TREASURE_TYPE;
typedef struct {
TREASURE_TYPE tr_type;
PRICE * tr_base_price;
const char * tr_name;
} TREASURE;
TREASURE Treasures[NUM_TREASURES];
void get_treasures(prices_file) {
if ((fp = fopen(prices_file, "r")) == NULL) {
ERROR_MESSAGE("Unable to open treasure prices file '%s' for reading", prices_file);
exit(1);
}
for (ttype = 0; ttype < NUM_TREASURES; ++ttype) {
Treasures[ttype].tr_type = ttype;
Treasures[ttype].tr_base_price = get_price(fp);
Treasures[ttype].tr_name = "I got nothing!";
}
fclose(fp);
}