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.
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.
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.
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"
>>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.
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.
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.