C 解析时忽略文件中的字符
我需要解析一个文本文件并处理数据。有效数据通常由带有TS的时间戳(后跟10个数字TS1040501134)或带有alpabet的值(后跟9个数字A098098)表示……因此,它类似于TS1040501134A111111B22222222……….TS1020304050A000000000 但是,在某些情况下,当没有数据时,会出现填充0。所以,这种情况可能是C 解析时忽略文件中的字符,c,string,parsing,gcc,C,String,Parsing,Gcc,我需要解析一个文本文件并处理数据。有效数据通常由带有TS的时间戳(后跟10个数字TS1040501134)或带有alpabet的值(后跟9个数字A098098)表示……因此,它类似于TS1040501134A111111B22222222……….TS1020304050A000000000 但是,在某些情况下,当没有数据时,会出现填充0。所以,这种情况可能是 00000000000000000000TS1040501134A111111111B2222222220000000000TS10203
00000000000000000000TS1040501134A111111111B2222222220000000000TS1020304050A000000000........`
现在我们可以看到,我需要忽略这些零。我该怎么做?我使用的是gnu C。您应该能够将文件读入字符串,然后使用strnstr在其中定位TS子字符串。strnstr返回的字符串将是时间戳的开始
要查找下一个时间戳,请在同一缓冲区中刚找到的字符串后面的指针处启动strnstr。如果处理多个字符串,则必须处理单个时间戳被拆分为多个字符串的情况。您应该能够将文件读入字符串,然后使用strnstr在其中定位TS子字符串。strnstr返回的字符串将是时间戳的开始
要查找下一个时间戳,请在同一缓冲区中刚找到的字符串后面的指针处启动strnstr。如果要处理多个字符串,则必须处理单个时间戳被拆分为多个字符串的情况。我第一次尝试使用类似于 大约20年。。。因此,下面的内容充其量只是伪代码 读一行文字,然后
char timestamp[11]; timestamp[10] = '\0';
char number[10]; number[9] = '\0';
for (i = 0 ; i < strlen(text); ) {
if isAlpha(text[i]) {
if text[i] == 'T' & text[i+1] == 'S' {
memcpy(timestamp, text[i+2], 10)
/* do whatever you do with a timestamp */
i += 12 /* Skip over timestamp */
} else {
memcpy(number, text[i+1], 9)
/* do whatever you do with a number */
i += 10 /* Skip over number */
}
} else {
if text[i] != '0' {
/* handle the error - should not get here */
}
i++ /* move to next character */
}
如果行不必包含完整的字符串,例如一行以TS10405和
下一行以01134开头,您必须编写额外的代码来管理文本缓冲区的正确刷新。我第一次尝试使用类似于 大约20年。。。因此,下面的内容充其量只是伪代码 读一行文字,然后
char timestamp[11]; timestamp[10] = '\0';
char number[10]; number[9] = '\0';
for (i = 0 ; i < strlen(text); ) {
if isAlpha(text[i]) {
if text[i] == 'T' & text[i+1] == 'S' {
memcpy(timestamp, text[i+2], 10)
/* do whatever you do with a timestamp */
i += 12 /* Skip over timestamp */
} else {
memcpy(number, text[i+1], 9)
/* do whatever you do with a number */
i += 10 /* Skip over number */
}
} else {
if text[i] != '0' {
/* handle the error - should not get here */
}
i++ /* move to next character */
}
如果行不必包含完整的字符串,例如一行以TS10405和
下一行以01134开头,您必须编写额外的代码来管理文本缓冲区的正确刷新。@WhirlWind。你会建议使用。。。批评是受欢迎的,但至少要有建设性的指导意义;始终使用字符串函数的长度限制变体。@WhirlWind。你会建议使用。。。批评是受欢迎的,但至少要有建设性的指导意义;始终使用字符串函数的长度限制变体。