read next line

Hi
OK, i have txt file with this details

FILE:
Orange
red
blue

now i know how can i get all line with EOF() in while loop.
my question is how can get line one by one with my command? i mean for example when i enter 1 program goes for next line and show me the next line?
i will be grateful for help.


Last edited on
Hi raminlich

there are so many ways to do that.

and i wrote an easy program:

The function is opening a file 123.txt (put 123.txt into the source code folder or specify the path such like /home/123.txt or D:\123.txt").

Here is my code on C:

The program will read the first line , and press enter to next line.
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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
	char buf[100];
	FILE *file;
	file = fopen("123.txt","r");  //specify path for the first argument.
	if(!file)
	{
		puts("Cannot read the file.");
		getchar(); //enter to exit.
		return -1;
	}
	while( fgets(buf,sizeof(buf),file) )	//do until EOF
	{
		if(buf[ strlen(buf)-1 ] == '\n')  //if there is '\n' 
			buf[ strlen(buf)-1 ]= 0;  //replace '\n' with '\0'
		printf("%s",buf);
		getchar(); // enter to next line.
	}
	puts("End of file , enter to exit...\n");
	getchar();//enter to exit.
        fclose(file);
	return 0;
}


fgets would read a line , but there is something you have to know.

For example the details of "123.txt" is:

Orange
red
blue

while you have read first line Orange to array named "buf"

In the array was put like this

'O' 'r' 'a' 'n' 'g' 'e' '\n' '\0'

next

'r' 'e' 'd' '\n' '\0'

next

'b' 'l' 'u' 'e' '\0'

as you can see, there is a '\n' character when it's not last string , sometimes we don't want to put the '\n' in the end of string , so we could replace it with '\0' or something you want.

well , if you think that '\n' doesn't influence to your program , forget it :)

C++ is simply for this problem.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
	fstream file;
	file.open("123.txt",ios_base::in);
	string str;
	if(!file.is_open())
	{
		cout << "Cant read the file.\n";
		cin.ignore(); //enter to exit.
		return -1;
	}
	while( getline(file,str) )
	{
		cout << str ;
		cin.ignore(); //enter to next line
	}
	cout << "End of file , enter to exit...\n";
	cin.ignore(); //enter to exit.
	file.close();
	return 0;
}

In this case you dont care about '\n' is read or not.

getline would make everything good.
Last edited on
Topic archived. No new replies allowed.