如何打开文件&用c解析它? [英] how to open file & parse it in c?
问题描述
我正在尝试打开此文件(final.txt)&阅读内容
?c0001
?f260
?L
D11
H30
R0000
C0040
1X1100000100010B300300003003
181100202900027部分否
181100202900097 [PRTNUM]
1e5504002400030B
1X1100002300010L300003
191100202000030数量
191100202000080 [QUANTY] >
1e5504001500040B
1X1100001400010L300003
1X1100001400150L003090
191100202000170P.O.No
191100202000220 [PONUMB]
1e5504001500180B
191100201200030供应商
1e3304000700030B
1X1100000600010L300003
181100200300030Serial
181100200300090 [序列号]
171100300900190Rev
171100300300190 [REV]
171100300900240Units
171100300300240 [UNITS]
1X1100000100180L003130
Q0001
E
来自我只想阅读[ PRTNUM],[QUANTY],[PONUMB],[SERIAL],[UNITS]并将其替换为另一个文件中的其他内容。
我写了以下c程序
fPOut = fopen( final.txt , r);
if (fPOut)
{
printf( 文件为\ n \ n);
do
{
scanf( %c,& a [ 1 ]) ;
fgets(cString, 2000 ,fPOut);
char * cStart = strchr(cString,' [');
cStart ++;
char * cEnd = strtok(cString, ]);
cEnd = ' \0';
printf( %s,cStart);
i ++;
}
while (i< b);
}
fclose(fPOut);
}
但它不起作用请帮忙。
那是因为你假设你会在每一行找到'['和']'字符。你应该这样做:
char * cStart = strchr(cString,' [');
if (cStart)
{
// 找到开括号
* cStart ++ = ' \0' 跨度>; // 将字符串拆分为[
char * cEnd = strchr(cStart,' ]');
// 您可以在这里查看找到的近括号
// 如果不是则抛出异常
* cEnd = ' \0'; // 终止关键字
printf( 键:%s,值:%s,cString,cStart);
}
// 继续循环
hi i'm trying to open this file(final.txt) & read the contents
c0001
f260
L
D11
H30
R0000
C0040
1X1100000100010B300300003003
181100202900027Part No
181100202900097[PRTNUM]
1e5504002400030B
1X1100002300010L300003
191100202000030Quantity
191100202000080[QUANTY]
1e5504001500040B
1X1100001400010L300003
1X1100001400150L003090
191100202000170P.O.No
191100202000220[PONUMB]
1e5504001500180B
191100201200030Supplier
1e3304000700030B
1X1100000600010L300003
181100200300030Serial
181100200300090[SERIAL]
171100300900190Rev
171100300300190[REV]
171100300900240Units
171100300300240[UNITS]
1X1100000100180L003130
Q0001
E
from which i only want to read [PRTNUM], [QUANTY], [PONUMB],[SERIAL],[UNITS] and replace them with the other contents in another file.
i've write following c program
fPOut = fopen("final.txt", "r");
if(fPOut)
{
printf("The file is\n\n");
do
{
scanf("%c", &a[1]);
fgets(cString ,2000 ,fPOut);
char* cStart = strchr(cString, '[');
cStart++;
char* cEnd = strtok(cString, "]");
cEnd = '\0';
printf("%s",cStart);
i++;
}
while(i<b);
}
fclose(fPOut);
}
but it is not working please help.
That is because you are assuming you will find the '[' and ']' characters in each line. You should do it like this:
char* cStart = strchr(cString, '['); if (cStart) { // open bracket found *cStart++ = '\0'; // split the string at [ char* cEnd = strchr(cStart, ']'); // you could check here for the close bracket being found // and throw an exception if not *cEnd = '\0'; // terminate the keyword printf("Key: %s, Value: %s",cString, cStart); } // continue the loop
这篇关于如何打开文件&用c解析它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!