gpt4 book ai didi

检查下一行

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:53 24 4
gpt4 key购买 nike

我的文件包含多个格式如下的客户记录:

CUSTOMER ...
details...
details...
CUSTOMER...
details...
details...
details...
CUSTOMER...
.
.

我需要将文件分成两部分。目前,我对文件中的所有行进行计数并除以 2,然后检查该行是否以字符串 CUSTOMER 开头。

如果是,我如何打印 CUSTOMER 之前的所有行?

如果不是,我如何检查下一行是否以 CUSTOMER 开头?

我的代码:

int main(int argc, char *argv[])
{
char ioarea[1000];
int TotCustLines=0,i=0;

int reqLine=0;
int getLine=0;

if((inFile=fopen(argv[inFileName],"r"))==NULL)
printf("Failed to open input file");

while(fgets(ioarea,BUFFER_SIZE,inFile))
{
TotCustLines++;
}
}
if(TotCustLines/2==0)
reqLine=(TotCustLines/2);
else
reqLine=(TotCustLines/2)+1;
fseek(inFile,1,SEEK_SET);
while(fgets(ioarea,BUFFER_SIZE,inFile))
{
getLine++;
if(getLine==reqLine)
{
if(strncmp(getLine,"CUSTOMER RECORD",15)==0)
//How to write all the lines before customer record.
//If not how can i check next line.
}
}

请提出解决方案。我是 C 文件概念的新手。

最佳答案

您可以使用一种方法来读取文件,然后在结果行中搜索 CUSTOMER(或其他任何内容):

1) 获取文件大小(使用 fseek()/ftell() ),或使用示例 1 获取行数和最长行。
2) 为字符串数组创建和分配内存,char **buffer; 参见示例 2
3) 使用 fgets() 将文件读入数组,边读边通过 buffer[index] 进行索引。
4) 数组 buffer[] 现在包含文件中 index 行的计数。

您现在可以使用 strstr() 字符串比较函数在您存储的行中查找 CUSTOMER。

Example 1获取文件行数和最长行长度的方法(用于创建内存)

int cnt=0;
int len=0;
int keep=0;
char line[260];// == MAX_PATH_LEN in windows, pick longer value if needed.
while(fgets(line, 260, fp))//get each line in file
{
len = strlen(line);//track length of each new line
if(len > keep) keep = len;//keep only longest line
cnt++;
} //keep will have value for longest line, cnt will have number of lines

示例 2 为 C 字符串数组 (char **string;) 创建内存:

注意:调用函数创建和调用示例:

char **variable = {0};  
int cnt, maxlen;
variable = allocMemoryStr(variable, &cnt, &maxlen);

........

char ** allocMemoryStr(char **strings, int numStrings, int maxLen)
{
int i;
strings = calloc(numStrings, sizeof(char*));// create pointers to arrays
for(i=0;i<numStrings; i++)
{
strings[i] = calloc(maxLen + 1, sizeof(char));// create memory for each array
}
return strings;
}

关于检查下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26738442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com