[英]How can I read specific lines in a file?
In a file, words like this are written:在一个文件中,写着这样的词:
Name
Surname
Age
Job
Telephone
James
Cooper
26
engineer
6545654565
Bob
Allen
22
doctor
5656555655
....
I want to print specific parts from these lines (for examples only names).我想从这些行打印特定部分(仅用于示例名称)。 I have tried this code but I can only print 1 line I want.我已经尝试过这段代码,但我只能打印我想要的 1 行。 (I print only James but I want to print all names: James, Bob,...). (我只打印 James,但我想打印所有名字:James、Bob、...)。
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int lineNumber;
static const char filename[] = "hayat.txt";
for(lineNumber=5;lineNumber<20;lineNumber+5);
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
if (count == lineNumber)
{
printf("\n %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
How can I do this?我怎样才能做到这一点?
I tried to make it work writing the code the most similar to the code in the question.我试图让它编写与问题中的代码最相似的代码。 This might not be the optimal solution but should work.这可能不是最佳解决方案,但应该可以。
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define TAMLINE 256
int main(void){
int lineNumber, count=0;
static const char filename[] = "hayat.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL ){
char line[TAMLINE];
/* //use this if you want to skip first 5 lines
for(int i=0;i<5;i++){
fgets(line, TAMLINE, file)
}
*/
while (fgets(line, TAMLINE, file) != NULL){
count ++;
//only print 1st line, 6th line 11 line.. ie lines with names
if (count%5 == 1){
printf("%s", line);
}
}
fclose(file);
}
return 0;
}
You only print once because that's exactly what are telling the programm to do您只打印一次,因为这正是告诉程序要做的事情
if linenumber == count ... print
else count++
will always print only one line.将始终只打印一行。
As for how to print difference categories, you either find similarities ( like some Objects and all names start with a capital letter and no number) or you specify them in an array - which probably would not be what you would like.至于如何打印差异类别,您要么找到相似之处(例如某些对象,所有名称都以大写字母开头,没有数字),要么在数组中指定它们 - 这可能不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.