Durand
Durand

Reputation: 897

Reading in data from a string in C (like scanf)

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!

Upvotes: 1

Views: 3413

Answers (2)

Foo Bah
Foo Bah

Reputation: 26281

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

Upvotes: 0

Andrew White
Andrew White

Reputation: 53516

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.

Upvotes: 2

Related Questions