我试图在循环中读取每行的文件并将值存储在结构中。当fscanf面对一个空字符串时,它会读取所有内容直到行尾,并且该行中的其他字段读为零。有没有办法指定fscanf将空间作为字段读取。下面的例子,
File.db:
tick31486081-tick31486081.mtd ,00:00:00:00:01:0e-31486081 , ,0,0,245
tick31486096-tick31486107-video1.ts ,00:00:00:00:01:0e-31486081 , ,1155072,5005312,5005312
tick31486080-tick31486080.mtd ,00:00:00:00:01:0e-31486080 , ,0,0,271
阅读数据后:
tick31486081-tick31486081.mtd , 00:00:00:00:01:0e-31486081 , **,0,0,245** ,0,0,0
tick31486096-tick31486107-video1.ts , 00:00:00:00:01:0e-31486081 , **,1155072,5005312,5005312** ,0,0,0
tick31486080-tick31486080.mtd , 00:00:00:00:01:0e-31486080 , **,0,0,271** ,0,0,0
有没有办法处理这个问题而不是忽略读取字段的空间?
FILE *fp = fopen (FILE, "r");
if (fp)
{
int retval;
int numRead = 0;
while (numRead != EOF)
{
Node_t *node = calloc (1, sizeof(Node_t));
if (node)
{
numRead = fscanf (fp, "%40s ,%30s ,%33s ,%d,%d,%d\n",
node->name, node->reid, node->hash,
&node->startOffset, &node->stopOffset, &node->length);
printf(" %s ,%s ,%s ,%d,%d,%d",
node->name, node->reid, node->hash,
node->startOffset, node->stopOffset, node->length);
}
}
retval = fclose (fp);
}
对于将从前3个字符串值中删除逗号分隔符的格式说明符,请使用“%[^,],%[^,],%[^,],%d,%d,%d \ n”。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[250], name2[250], name3[250];
int one, two, three;
FILE *f;
f = fopen("text.txt", "r");
if(f) {
int numRead = 0;
while (numRead != EOF) {
numRead = fscanf(f, "%[^,],%[^,],%[^,],%d,%d,%d\n", name, name2, name3, &one, &two, &three);
printf("name:%s name2:%s name3:%s one:%d two:%d three:%d\n", name, name2, name3, one, two, three);
printf("name:%d name2:%d name3:%d\n", (int) strlen(name), (int) strlen(name2), (int) strlen(name3));
}
fclose(f);
}
else {
printf("failed to open file\n");
}
return 0;
}
我认为你也可以用fscanf-format-specifier替换\ n。
祝好运!