0

Hi,
I have a file in C which has many lines. I want to store each line separately so that i can reference it later with a char *host.
How can i do that?

Thanks.

Edited by adrawat: n/a

4
Contributors
5
Replies
8
Views
7 Years
Discussion Span
Last Post by WaltP
1

Create an array of pointers, then read each line and add to the array

char *data[200]; // 200 lines of data
char line[255]; // one line from the data file
fgets(line, sizeof(line), fin);
data[0] = malloc( strlen(line) +1);
strcpy(data[0], line);

Now put the above in a loop so that it reads the entire file. Increase the array size if needed so that it will hold all the lines in the file.

Votes + Comments
If the OP is happy, I call it a good enough post.
Amazing answer !!!
Nonsense
-1

Create an array of pointers, then read each line and add to the array

[...]

Now put the above in a loop so that it reads the entire file. Increase the array size if needed so that it will hold all the lines in the file.

Perhaps, a second more attentive read of the post might help you to realize that that's not what the OP is asking for. Specially, the part that says...

I want to store each line separately

Don't say just: "...put it in a loop"

Edited by Aia: n/a

Votes + Comments
Call it nonsense if you want, but that's the general way to do it.
0

>>I want to store each line separately

@Aia: I'm not sure exactly what he meant by that, do you? My guess was that he wanted to store the lines in memory. One way would be to declare a whole bunch of pointers, but a more reasonable way is to store them in an array of pointers. I also assumed (maybe wrongly) that the OP has a brain and he/she can use it to figure out how to put the code I posted in a loop. But maybe that was just asking too much.

Like anything else there are other ways to do it, such as linked lists. But I doubt the OP knows anything about them -- yet.

Edited by Ancient Dragon: n/a

Votes + Comments
"That's the general idea for you". Broken code and half ways are you cup of tea.
0

I do not know why every post that i put...there are always controversies..maybe my question was ambiguous.
The reply by Ancient Dragon is absolutely what i was looking for.
Actually the file contains IP addresses of diff servers on diff lines and i need to store each IP address in *host so that i can use a loop to connect to each server one by one.

Thanks to Aia also.

1

I do not know why every post that i put...there are always controversies..maybe my question was ambiguous..

The more details you give -- with examples, restrictions, and when/where/what, the less ambiguous your question. Remember, only you know what you're doing. If you don't explain it to us well enough, controversy happens.

Votes + Comments
controversy! woot!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.