【发布时间】:2017-06-30 18:46:43
【问题描述】:
我有一个txt文件,它的行如下
[7 chars string][whitespace][5 chars string][whitespace][integer]
我想使用 fscanf() 将所有这些读入内存,但我对应该使用什么格式感到困惑。
这是这样一行的一个例子:
hello box 94324
注意每个字符串中的填充空格,除了分隔空格。
编辑:我知道首先使用 fgets() 的建议,我不能在这里使用它。
编辑:这是我的代码
typedef struct Product {
char* id; //Product ID number. This is the key of the search tree.
char* productName; //Name of the product.
int currentQuantity; //How many items are there in stock, currently.
} Product;
int main()
{
FILE *initial_inventory_file = NULL;
Product product = { NULL, NULL, 0 };
//open file
initial_inventory_file = fopen(INITIAL_INVENTORY_FILE_NAME, "r");
product.id = malloc(sizeof(char) * 10); //- Product ID: 9 digits exactly. (10 for null character)
product.productName = malloc(sizeof(char) * 11); //- Product name: 10 chars exactly.
//go through each line in inital inventory
while (fscanf(initial_inventory_file, "%9c %10c %i", product.id, product.productName, &product.currentQuantity) != EOF)
{
printf("%9c %10c %i\n", product.id, product.productName, product.currentQuantity);
}
//cleanup...
...
}
这是一个文件示例:(实际上是 10 个字符、9 个字符和 int)
022456789 box-large 1234
023356789 cart-small 1234
023456789 box 1234
985477321 dog food 2
987644421 cat food 5555
987654320 snaks 4444
987654321 crate 9999
987654322 pillows 44
【问题讨论】:
-
@BLUEPIXY 有一个很好的comment - 一定要检查
fscanf()的返回值。 -
当你说你必须使用 f/scanf 而你不能使用 fgets 时,我认为这是你正在上课的一个作业。如果是这样,请帮自己一个忙,一旦结束就忘记这一课。在现实世界的 C 编程中,基本上 nobody 使用
scanf或fscanf做任何事情。它们实际上没用。我会说学习它们完全是浪费时间,但我无法影响你的导师。 -
关于
fgets()的一个关键问题,fscanf()的问题以及此类帖子是错误处理之一。当输入unexpected时,代码应该怎么做?这篇文章的中心是如何读取预期的输入,但没有解决输入是否可能可以使用"hello \n box 94324\n"、"hello (many space) box 94324\n"、"hello \n box\n"或"hello \n box XYZ\n"。祝你好运。 -
@DavidBowling 旁白:“值得学习 fscanf(),如果只是能够使用 sscanf()”不如“学习有用的函数
sscanf()”那么直接也许 i> 学习fscanf()或跳过后者。(f)scanf()不需要被视为sscanf()的先决条件。 -
在调用任何
scanf()系列函数时,始终检查返回值(而不是参数值)以确保操作成功。在当前场景下,返回值必须为3,否则会出错。
标签: c