[英]Read a specific range of lines from a file using c
I have the following content in a file: 我的文件中包含以下内容:
hhasfghgsafjgfhgfhjf
gashghfdgdfhgfhjasgfgfhsgfjdg
jfshafghgfgfhfsghfgffsjgfj
.
.
.
.
.
startread
hajshjsfhajfhjkashfjf
hasjgfhgHGASFHGSHF
hsafghfsaghgf
.
.
.
.
.
stopread
.
.
.
.
.
.
jsfjhfhjgfsjhfgjhsajhdsa
jhasjhsdabjhsagshaasgjasdhjk
jkdsdsahghjdashjsfahjfsd
I need to read the lines from the next line of startread
till the previous line of stopread
using ac code and store it to a string variable(of course with a \\n
for every line breaks). 我需要使用ac代码读取从
startread
的下一行到startread
的上一行的stopread
行,并将其存储到字符串变量(当然,每个换行符都带有\\n
)。 How can i achieve this? 我怎样才能做到这一点? I have used
fgets(line,sizeof(line),file);
我用过
fgets(line,sizeof(line),file);
but it starts reading from the beginning. 但它从头开始阅读。 I don't have the exact line number to start and stop reading since the file is written by another C code.
由于文件是由另一个C代码编写的,因此我没有确切的行号来开始和停止读取。 But there are these identifiers
startread
and stopread
to identify whereto start reading. 但是,这些标识符有
startread
和stopread
来标识从stopread
开始读取。 Operating platform is linux. 操作平台是linux。 Thanks in advance.
提前致谢。
Use strcmp()
to detect startread
and stopread
. 使用
strcmp()
来检测startread
和stopread
。 Ignore all lines read until "startread"
is read and then store all lines until "stopread"
is read: 忽略所有读取的行,直到读取
"startread"
,然后存储所有行,直到读取"stopread"
:
/* Read until "startread". */
char line[1024];
while (fgets(line, sizeof(line), file) &&
0 != strcmp(line, "startread\n"));
/* Read until "stopread", only if "startread" found. */
if (0 == strcmp(line, "startread\n"))
{
while (fgets(line, sizeof(line), file) &&
0 != strcmp(line, "stopread\n"))
{
/* Do something with 'line'. */
}
}
#define MAX_BUF_LEN 1000
int flag=0;
while(fgets(buf, MAX_BUF_LEN, file) != NULL){
if(strncmp(buf, "startread", strlen("startread")) == 0){
flag=1;
}
else if (strncmp(buf, "stopread", strlen("stopread")) == 0){
flag=0;
}
if(flag){
strncpy(line, buf, strlen(buf));
// strncat(line, '\n', strlen('\n'));
}
// that's all!
}
fclose(file);
This should works. 这应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.