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 contentsc0001f260LD11H30R0000C00401X1100000100010B300300003003181100202900027Part No181100202900097[PRTNUM]1e5504002400030B1X1100002300010L300003191100202000030Quantity191100202000080[QUANTY]1e5504001500040B1X1100001400010L3000031X1100001400150L003090191100202000170P.O.No191100202000220[PONUMB]1e5504001500180B191100201200030Supplier1e3304000700030B1X1100000600010L300003181100200300030Serial181100200300090[SERIAL]171100300900190Rev171100300300190[REV]171100300900240Units171100300300240[UNITS]1X1100000100180L003130Q0001Efrom 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 programfPOut = 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 这篇关于如何打开文件&amp;用c解析它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-14 17:46