1

I've read in and stored a data file that I am processing into an array of char arrays, one char array for each line in the file and I now want to process the individual lines. I'm not however sure how to do this.

I read each line in like so:

/* Read the whole file into an array */
char read_lines[FILE_LENGTH][FILE_WIDTH];
for(i=0;i<FILE_LENGTH;i++) {
    fscanf(data_file, "%[^\n]", read_lines[i]);
    fscanf(data_file, "%[\n]", dump);
}

I need to read the data in each line which is formatted as %d\t%d\t%d\t%d\t%d and I'm not really sure how to read a specific variable into a scanf function. I know that fscanf() reads from a file and scanf() reads from user input, is there a function that reads from a variable?

I come from a python background and in python, I would just use the following code:

read_lines = open('file.txt').readlines()
for line in lines:
    i = lines.index(line)
    first[i], second[i], third[i], forth[i], fifth[i] = line.split('\t')

I really cannot see how to do the equivalent in C. I've done a fair bit of research but I couldn't find anything useful. Any help would be appreciated!

Thanks!

2 Answers 2

2

Perhaps check out sscanf. It is just like it's cousin scanf and fscanf but takes a string instead. Here is a snip from the above link.

The sscanf function accepts a string from which to read input, then, in a manner similar to printf and related functions, it accepts a template string and a series of related arguments. It tries to match the template string to the string from which it is reading input, using conversion specifier like those of printf.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh! Thanks a lot, sscanf didn't seem to come up in my searches, this is exactly what I need.
0

You can use the strtok function [read the manpage] to split a string

e.g. http://www.gnu.org/s/libc/manual/html_node/Finding-Tokens-in-a-String.html

3 Comments

Thanks, this is quite useful, I'll probably use this in the future but I think using sscanf() is probably a simpler option in C whereas I chose to use split() in python because it was the simpler choice there.
@Durand you can do a similar thing in python -- also, the python code you gave doesnt automatically interpret the fields as integers
Yeah, you would need to use: first[i], second[i], third[i], forth[i], fifth[i] = [int(i) for in line.split('\t')]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.