Read csv file using fscanf in C - c

I have to read a csv file using fscanf function (I cant use any other function like strtok_s to parse the line) and im having the following problem.
Here is the code:
fp1 = fopen (argv [1],"r");
var = fscanf (fp1,"%d,%d,%[^,]s,%[^,]s",&aux.points,%aux.titles,aux.name,aux.nation);
I'm trying to print each parameter in the screen. There is no problem with the integers and even with the first string (name) but nothing is stored in the next string (nation).
I assume that the first %[^,]s is stopping the execution of the whole fscanf function so the next string is never read. Any idea? I have tried everything but this is just not working.

Try this as the string:
"%d,%d,%[^,],%[^,]"
I eliminated the "s" because [...] acts as the specifier.
Think of the [...] as a super s.

Related

Read last line of a text file - C programming

I'm still a novice in C as I just started out. Here is a part of my function to open the file and then save the file lines into variables. I did while to loop until the end of file so I can get the last line, however it did not go as expected. So, I was wondering how can I get just the last line from a text file? Thank you.
tfptr = fopen("trans.txt", "r");
while (!feof(tfptr)){
fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);
}
fclose(tfptr);
sample text file:
0:1:7.98
1:1:20.97
2:1:35.96
2:2:44.95
2:2:44.95
3:2:55.94
In your fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);, the %.2f will cause problem.
You can't specify the precision for floating-point numbers in scanf() unlike in the case of printf(). See this answer.
So, instead of %.2f in the scanf format string, use just %f.
Since you just need the last line, you could just read the file line by line with fgets() and keep the last line.
while( fgets(str, sizeof(str), tfptr)!=NULL );
printf("\nLast line: %s", str);
fgets() will return NULL when the file is over (or if some error occurred while reading).
The lines in the input file are read one by one and when there are no more lines to read, str (a character array of suitable size) will have the line that was read last.
You could then parse the string in str with sscanf() like
sscanf(str, "%u:%u:%f", &combo_trans, &ala_trans, &grand_total);
Also, you should be checking the return value of fopen() to see if the file was really opened. fopen() will return NULL if some error occurred.
if( (tfptr = fopen("trans.txt", "r"))==NULL )
{
perrror("Error");
}
What did go wrong? Did you get another line?
Don't use "&" as you don't want to save a pointer. That can be the reason of failure.

Reading a file into an array in C

I would like to read a file called "input" with a lot of lines and 10 columns into an array using C. I wrote the following code:
FILE *file;
file=fopen("input","r");
i=0;
while ( fgetc(file) != EOF )
{
fscanf(file,"%e\t%e",&x[i],&y[i]);
i++;
}
The problem that I am ecoutering is that the first element of the file is not read. It is read however when the file contains an initial indent.
Could you help me?
Thank you in advance.
fgetc() reads a character and returns it and increments the file pointer. next when you call fscanf(), the first character won't be seen as its already past first character. If you want, only use fscanf() and check for EOF to detect end of file.

Reads only alphabetic chars with fscanf

Hello i have simply function to read from file
while(fscanf(fp," %255[a-zA-Z]",test) == 1)
{
puste = 1;
push(&drzewo,test);
}
It should read only words which contains only alphabetic characters and that works great. When I have for example a single number in my file my while loop quits; how should I change it?
Of course it stops, since the fscanf() call will fail to do the conversion you're requiring, and thus return 0. What would you expect it to do?
It's often better to read whole lines using fgets(), and then parse them "manually", that way it's easy to just do nothing and read another line if the desired data is not found.

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!
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.
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

C: fscanf erases integer variables values?

I've got a C program that encounters errors when I enter a while loop.
I initialize a variable (fragmentcount) and write into it using fscanf and assign it a value of 4 (this works)
int fragmentCount;
if ((fscanf(fp, "%i", &fragmentCount)) == 1) {
...
}
However, when I try to access it in a while loop below, fragmentCount = 0
while ((fscanf(fp, "%[#]", discards)) != EOF) {
printf(fragmentCount); // <- pseudocode
}
For a brief experiment, I tried taking away the fscanf as the conditional test for the while loop, and fragmentCount was the correct value (4).
Why is this so? How can I avoid this?
How is discards declared? It is possible that fscanf is reading more data than discards has room for, which might overwrite the value of other variables.
Using the '%[' format without a field width is a bad idea - it leaves your program open to buffer overflow errors.
fscanf reads a value from a file and interprets it according to the format string. The '%i' format string is unknown (perhaps you meant '%d'?) according to http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/, so you are unlikely to read the value you expect.
Apart from file FILE* and the format string, all parameters to fscanf are out parameters, which means the value they contain before the call to fscanf are irrelevant and could be replaced.

Resources