[英]Reading Comma Separated Values from File in C
I want to read this 我想读这个
zeyad,aar,eee,100,sss,55,science
toto,art,bb,100,ss,55,drawing
from a file then store it in a structure of books.title,books.publisher etc,, as shown below 从文件中存储,然后将其存储在books.title,books.publisher等结构中,如下所示
Can Somebody tell me how to not read the commas and just store string in its place? 有人可以告诉我如何不读取逗号而只将字符串存储在其位置吗? what I tried is using %*C between each string but it does not work.
我试过的是在每个字符串之间使用%* C,但是它不起作用。
while (!feof(pBook))
{
fscanf(pBook,"%s%*c%s%*c%s%*c%s%*c%s%*c%d%*c%s",
books[z].Title,books[z].Author,books[z].Publisher,books[z].ISBN,books[z].DOP,
&books[z].Copies,books[z].Category);
fscanf(pBook,"\n");
z++;
}
fclose(pBook);
A simple example (not tested): 一个简单的例子(未经测试):
void SeparateCommas(char *FileName)
{
FILE *fd = fopen(FileName, "r");
size_t len = 0;
ssize_t read;
char *line = NULL;
char temp[50][32];
char *token;
char *end_str;
while((read = getline(&line, &len, fd)) != -1)
{
printf("Read line: %s", line);
token = strtok_r(line, ",", &end_str);
while(token != NULL)
{
strncpy(temp[i], token, sizeof(temp[i]));
printf("Read word: %s", temp[i]);
token = strtok_r(NULL, ",", &end_str);
i++;
}
}
}
Can Somebody tell me how to not read the commas and just store string in its place?
有人可以告诉我如何不读取逗号而只将字符串存储在其位置吗?
Since %s
matches a sequence of non-white-space characters , it cannot be used to not read the commas . 由于
%s
与非空格字符序列匹配,因此不能将其用于不读取逗号 。 For your purposes %[…]
, which matches a nonempty sequence of characters from a set of expected characters (the scanset ) , can be used, whereby the character after the left bracket is a circumflex (^), in which case the scanset contains all characters that do not appear between the circumflex and the right bracket : 为了您的目的,可以使用
%[…]
,它与一组预期字符( scanset )中的一个非空字符序列匹配 ,因此左括号后的 字符为抑 音符(^),在这种情况下,scanset包含所有不在 抑音符和右括号之间的 字符 :
while (fscanf(pBook, "%[^,],%[^,],%[^,],%[^,],%[^,],%d,%s\n",
books[z].Title, books[z].Author, books[z].Publisher, books[z].ISBN,
books[z].DOP, &books[z].Copies, books[z].Category) == 7) ++z;
I assume you ensured that all strings in the input file fit into the size reserved for their respective structure element, otherwise you would have used a maximum field width . 我假设您确保输入文件中的所有字符串都适合为其各自的结构元素保留的大小,否则您将使用最大字段宽度 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.