Reading txt and printing wanted value

Hey, I have small problem.. How I can read/print only wanted line/value from file? At the moment when I run it.. it prints whole file (cause of EOF yes) but couldn't figure right one.. :/

Messy question.. but shortly: if user input is "Hamina" it search from file if there is any "Hamina" word and prints it and all numbers after it before next word begins

Hopefully someone understanded what I meant! Thanks:) (sorry c not c++)
1
2
3
4
Hamina;2014-04-14;7;
Hanko;2014-04-14;10.53;
Haukipudas;2014-04-14;4.77;
Heinola;2014-04-14;7.83;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 FILE *AvaaTiedosto(char nimi[], char kasittelytapa[]);

int main(void)
{
	setlocale (LC_ALL , "finnish");

	int energiakulutus = 0;
	energiakulutus = funktio(energiakulutus);

	char kaupunki;
	FILE *tiedosto;
	char saatieto;
	tiedosto = AvaaTiedosto("saatieto.txt", "r"); // lukumoodi

	printf("Valitse kaupunki: ");
	scanf("%s" , &kaupunki);
	kaupunki = fgetc(tiedosto);

	while (kaupunki != EOF)
	{
		printf("%c" , kaupunki);
		kaupunki = fgetc(tiedosto);
	}
	fclose(tiedosto);

	getch();
	return 0;
}
FILE *AvaaTiedosto(char nimi[], char kasittelytapa[])
{
	FILE *tdsto;

	tdsto = fopen(nimi, kasittelytapa);
	if(tdsto == NULL)
	{
		printf("ERROR");
		_getch();
	}
	
	return tdsto;
}
You can read only one line/chosen line from file.
You will have to read all lines one by one, with search of required phrase in the read line.

Use strstr or similar function see if required word is part of the read line
Hi,

Try with the following code,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int main()
{
	setlocale (LC_ALL , "finnish");		
	FILE *tiedosto = AvaaTiedosto("saatieto.txt", "r"); // lukumoodi

	printf("Valitse kaupunki: ");

	char kaupunki[64];//store input stirng
	::memset(kaupunki,0,sizeof(char)*64);	
	scanf("%s" , &kaupunki);

	size_t kaupunkiLen=strlen(kaupunki);	
	int index=0;

	for(char ch = fgetc(tiedosto);ch != EOF;ch = fgetc(tiedosto))
	{
		if(ch==kaupunki[index])//compare with input string
		{
			++index;
			if(index==kaupunkiLen)//Matches with input string
			{
				for(size_t j=0;j<kaupunkiLen;j++)//output input string
					printf("%c",kaupunki[j]);				

				for(char ch1 = fgetc(tiedosto);ch1 != EOF && ch1!='\n';ch1 = fgetc(tiedosto))//output upto endof the line
					printf("%c",ch1);

				break;
			}
		}
		else
			index=0;		
	}

	fclose(tiedosto);

	getch();
	return 0;
}


Output:

Valitse kaupunki: Heinola
Heinola;2014-04-14;7.83;


Let me know if u have any issues with above code.
Last edited on
Thank you very much! You saved my day (and coffee).. :)
Works like I wanted to.. still need to make it look for date too, but think I'll manage with this code.
Topic archived. No new replies allowed.