Reputation: 21
I have a file like this from which I need some values from its last line. This is the file:
XFOIL Version 6.96 Calculated polar for: pane 1 1 Reynolds number fixed Mach number fixed xtrf = 1.000 (top) 1.000 (bottom) Mach = 0.000 Re = 0.100 e 6 Ncrit = 4.000 alpha CL CD CDp CM Top_Xtr Bot_Xtr ------ -------- --------- --------- -------- -------- -------- 0.000 0.3882 0.01268 0.00440 -0.0796 0.6713 1.0000
What I want to do is to read the values of alpha
, CL
and CD
located in the last line.
I use this code
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE * pFile;
FILE * test1;
char ch;
double alpha,lift,drag;
int i;
pFile = fopen("save.txt","r");
test1 = fopen("test1.txt","w");
fseek ( pFile , 434 , SEEK_SET );
while( ( ch = fgetc(pFile) ) != EOF ){
fputc(ch, test1);
}
for(i = 0; i < 3; i++)
{
fscanf(test1, "%lf ",&alpha);
fscanf(test1, "%lf ",&lift);
fscanf(test1, "%lf",&drag);
}
printf("alpha = %lf cl = %lf cd = %lf",alpha,lift,drag);
fclose(test1);
fclose ( pFile );
return 0;
}
Thank you in advance...
Guys thank you all for your answers what i forgot
to mention is that it prints out that alpha = 0.00000 cl = 0.00000 cd = 0.00000 which actually are non zero but 0.000 0.3882 0.01268 respectivelly...!!
Upvotes: 0
Views: 175
Reputation: 333294
pFile = fopen("save.txt","r");
test1 = fopen("test1.txt","w");
You are opening save.txt
for reading, and test1.txt
for writing.
fseek ( pFile , 434 , SEEK_SET );
while( ( ch = fgetc(pFile) ) != EOF ){
fputc(ch, test1);
}
You are now skipping to character 434 in save.txt
, and then reading the rest of the file, printing each character out into test1.txt
.
for(i = 0; i < 3; i++)
{
fscanf(test1, "%lf ",&alpha);
fscanf(test1, "%lf ",&lift);
fscanf(test1, "%lf",&drag);
}
You are now trying to read from test1.txt
, but it is open for writing, and the current position is at the end of the file. If you want to read it, you will need to either close it and open it for reading, or open it read-write (fopen(..., "rw")
) up above and then reset the current position to the beginning of the file before starting to read (it is undefined what will happen if you don't do that).
In fact, you shouldn't need to skip to a byte offset, copy the last line into a different file, and then read that new file. You can just read the last line directly from the original file. No need for that loop that reads from one file into another; just run your scanf()
on the original file.
Remember to check your function calls for errors. The scanf()
calls that you made probably returned an error. You can check for an error with ferror(file)
, and get the actual error message with strerror(errno)
.
Upvotes: 3