问题描述
我正在尝试从输入文件"Test.txt"中提取一系列文本
范围从存储在pfst [0]中的字符串的出现开始到存储在pfet [0]中的字符串的开始.最终的o/p存储在文件"PerformSectionExtract.txt"中.
字符串值在解析之前可以正常打印,但是在进入解析机制之后,可以打印NULL值.以下是我的代码:
Hi,
I am trying to extract a range of text from an input file "Test.txt"
The range starts from the occurrence of a string stored in pfst[0] till the string stored in pfet[0]. The final o/p is stored in the file "PerformSectionExtract.txt".
The string values prints fine before the parsing, but NULL values are printed after entering the parsing mechanism. Below is my code :
char pfst[1500][50];
char pfet[1500][50];
char fileOrig[MAX_PATH] = "Test.txt";
char fileRepl2[MAX_PATH] = "PerformSectionExtract.txt";
FILE *fp1, *fp2, *fp3, *fp4;
fp1 = fopen(fileOrig,"r+");
fp4 = fopen(fileRepl2,"w+");
while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1))
{
strcpy(buffer2,buffer);
length= strlen(pfst[0])-1;
if(strncmp(buffer2, pfst[0], length ) == 0 )
{
found2=1;
}
if(found2 ==1)
{
sprintf(buffer4," %s",buffer);
fputs(buffer4,fp4);
if(strstr(buffer,pfet[0]) != NULL)
{
found2 = 0;
count2++;
}
}
}
当我对字符串进行如下硬编码时,代码可以正常工作
The code works fine when I hard code the string as below
if(strncmp(buffer2, "string entered here", length ) == 0 )
但是,这不会达到目的..:-(
预先感谢,
Faez
But, this won''t serve the purpose.. :-(
Thanks in advance,
Faez
推荐答案
FILE *fpIn, *fpOut;
char pfst[10][50];
char pfet[10][50];
char buffer[MAX_LEN_SINGLE_LINE];
int length;
char* tok;
int found = 0;
fpIn = fopen("Test.txt", "r");
fpOut = fopen("PerformSectionExtract.txt","w");
while(fgets(buffer, MAX_LEN_SINGLE_LINE, fpIn))
{
if(strncmp(buffer,"PERFORM",7) == 0 )
{
fputs(" ", fpOut);
fputs(buffer, fpOut);
tok = strtok(buffer + 8, ".\n");
if (tok != NULL)
{
sprintf(pfst[0], "%s SECTION", tok);
sprintf(pfet[0], "%s -EXIT", tok);
// i++, j++, p++;
}
continue;
}
length = strlen(pfst[0]);
if(strncmp(buffer, pfst[0], length ) == 0 )
{
found = 1;
}
if (found == 1)
{
fputs(" ", fpOut);
fputs(buffer, fpOut);
if(strstr(buffer, pfet[0]) != NULL)
{
found = 0;
// count2++;
}
}
}
Test.txt
Test.txt
PERFORM test1
blah blah blah
test1 SECTION
test1 1
test1 2
test1 3
test1 -EXIT
ignored stuff 1
ignored stuff 2
ignored stuff 3
PERFORM nextTest
more ignored stuff 1
more ignored stuff 2
more ignored stuff 3
nextTest SECTION
nextTest 1
nextTest 2
nextTest 3
nextTest -EXIT
PerformSectionExtract.txt
PerformSectionExtract.txt
PERFORM test1
test1 SECTION
test1 1
test1 2
test1 3
test1 -EXIT
PERFORM nextTest
nextTest SECTION
nextTest 1
nextTest 2
nextTest 3
nextTest -EXIT
pfst[0]
和
pfet[0]
这篇关于如何从文件中提取文本范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!