Yoav
Yoav

Reputation: 115

fprintf prints a new line at the beginning of the file

I'm using a fprintf function to print to a new file

I'm using the following command to write multiple times:

fprintf(fp, "%-25s %d %.2f %d",temp->data.name, temp->data.day, temp->data.temp, temp->data.speed);

The problem is that sometimes the file gets an extra new line as the first character. Could this be lelftovers from some buffer, I don't really know...

typedef struct Data {
    char name[26];
    int day;
    int speed;
    float temp;
} Data ;

@spatz you were right, I'm kind of new to the string format thing and I was told to make one for a fscanf where I was to expect an undetermined amount of space between the bits of data, here is what I came up with, I'm pretty sure its the source of the problem:

check=fscanf(fp1, "%20c%*[^0-9]%d%*[^0-9]%f%*[^0-9]%d%*[^\n]%*c", name, &day, &temp, &speed);

only the first line get read normally and everything afterwards reads the new line of the previous line.

Can someone please show me the proper way to write this thing?

Upvotes: 2

Views: 1870

Answers (2)

drrlvn
drrlvn

Reputation: 8437

Your problem is that name starts with a newline, and that newline ends up in the file.

In order to properly parse the file I would have to know its format, but for now I assume it's <string> <int> <int> <float> where the number of spaces between each element may vary.

The format string I would start with is simply "%s%d%d%f", and let fscanf() deal with the whitespace. With this format string I was able to properly parse lines like

foo     3   4 7  

If this does not satisfy you feel free to elaborate on the format of the file you are parsing and I'll try to come up with solutions.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249434

Rather than calling fscanf() over and over, and hoping that the newlines match up how you want, use fgets() to get one line at a time, parse it using fscanf(), and do error handling on a line-by-line basis. This will be less error-prone, and it sounds like it will clear up your problem with no extra effort.

Upvotes: 0

Related Questions