fscanf QT widget C++ - file-io

I got problem with fscanf function while reading camera parameters file. I'm using QT 4.7, writing QT widget application. I'm getting segmentation fault when executing first fscanf statement. But when I execute code in console application project it works good.
Here is part of my code:
struct parametry_kamery
{
float cc[2],fc[2],alpha_c,kc[5];
int D,al;
};
parametry_kamery kam_par;
void Widget::readParameters(parametry_kamery* kam_par)
{
FILE *fi;
char buf[255];
float cc1=0,cc2=0;
fi=fopen("Camera parameters.cfg", "r");
if(!fi)
{
QMessageBox::information(this,tr("Can't read file"),tr("Error"));
return;
}
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %f %f",buf,buf,buf,&cc1,&cc2);
kam_par->fc[0] = cc1;
kam_par->fc[1] = cc2;
fclose(fi);
}
I'm calling function readParameters(&kam_par);
And here is the content of file:
Parametry_wewnętrzne_kamery
Focal_Length: fc = 1079.33793 1181.44679 ± [ 2.44878 2.52105]
Principal_point: cc = 378.95649 245.99109 ± [ 3.48032 2.99878 ]
Skew: alpha_c = 0.00000 ± 0.00000 => angle of pixel axes = 90.00000 ± 0.00000 degrees
Distortion: kc = -0.13666 -0.01830 -0.00070 0.00134 0.00000

Your first fscanf is reading 3 strings and then 2 floats. But your file seems to start with 4 strings before the 2 floats. The first 4 strings are:
Parametry_wewnętrzne_kamery
Focal_Length:
fc
=
And by the way, when you are using Qt, it would be much easier (and less error-prone) to use Qt's file functions (QFile and QTextStream) and QString and its conversions functions.

I changed the function, now it takes structure by value and return structure, I know that it require more memory but works well for now. I will try to fix the version with pointer.
Great thanks for your help Roku.
Widget::parametry_kamery Widget::readParameters(parametry_kamery kam_par)
{
FILE *fi;
char buf[255];
fi=fopen("Camera parameters.cfg", "r");
if(!fi)
{
QMessageBox::information(this,tr("Błąd odczytu pliku konfiguracyjnego"),tr("Error"));
return parametry_kamery::parametry_kamery();
}
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %f %f",buf,buf,buf,&kam_par.fc[0],&kam_par.fc[1]);
QMessageBox::information(this,buf,buf2);
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %f %f",buf,buf,buf,&kam_par.cc[0],&kam_par.cc[1]);
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %f",buf,buf,buf,&kam_par.alpha_c);
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %f %f %f %f %f",buf,buf,buf,&kam_par.kc[0],
&kam_par.kc[1],&kam_par.kc[2],&kam_par.kc[3],&kam_par.kc[4]);
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %i",buf,buf,buf,&kam_par.D);
while('\n'!=fgetc(fi));
fscanf(fi,"%s %s %s %i",buf,buf,buf,&kam_par.al);
fclose(fi);
return kam_par;
}

Related

C - fprintf output is not consistent within for loop

I am printing a vary large dataset to a text file using fprintf:
FILE *ff23=fopen("parts_in_cell_dript_part.txt","wa");
if (ff23 == NULL)
error("Error opening text file");
int N=e->s->nr_parts;
fprintf (ff23,"%d\n",N);
for (int k = 0; k < N; k++) {
struct part *restrict p = &parts[k];
float xx=p->x[0];
float yy=p->x[1];
float zz=p->x[2];
int id;
id=p->id;
fprintf(ff23,"%d %f %f %f %d\n",k+1,xx,yy,zz,id);
}
fprintf(ff23,"Finished func\n");
fclose(ff23);
exit(1);
The output suffers from several problems:
lines overwrite other lines. The first column is should go consecutively from 1 to N.
more/less numbers are printed to the file than expected.
I have try to use only append but results stay the same.
EDIT:
I tried adding "t" mode, it did not help

Concatenating a string to make up an SQL query in C

I need to do this in two separate steps but so far I am not finding a way of doing this.
First, I need to convert a double variable, into a char variable (and to be saved in that variable). I have noticed type casting doesnt work the same in C as Java / other languages. How do I cast a variable to be a string / char?
Second, I need to concatenate the strings, there will be a total of 6 string variables that will need concatenating, I have only found the strcat function which only takes 2 arguments.
These are the strings I am trying to build:
char *queryOne = "INSERT INTO location (id, carid, ownerid, lat, long, speed) VALUES (,2, 1, ";
char *queryTwo = lat; // lat is a double
char *queryThree = ",";
char *queryFour = longatude; // longatude is a double
char *queryFive = ",";
char *querySix = speed; // speed is a double
And then I need the concatenated string to work in: (mysql_query(conn, query)) as one long string
Edit: So possibly, this should convert the datatype I think?
char buffer [50];
char *queryOne = "INSERT INTO location (id, carid, ownerid, lat, long, speed) VALUES (,2, 1, ";
char *queryTwo = sprintf (buffer, "%d", lat);
char *queryThree = ",";
char *queryFour = sprintf (buffer, "%d", longatude);
char *queryFive = ",";
char *querySix = sprintf (buffer, "%d", speed);
fprintf(stderr, "Dta: %s\n", queryOne);
fprintf(stderr, "Dta: %s\n", *queryTwo);
fprintf(stderr, "Dta: %s\n", queryThree);
fprintf(stderr, "Dta: %s\n", *queryFour);
fprintf(stderr, "Dta: %s\n", queryFive);
fprintf(stderr, "Dta: %s\n", *querySix);
In your case, you could use:
#define MAXSQL 256
char sql[MAXSQL];
snprintf(sql, MAXSQL, "%s %f , %f , %f", queryOne, lat, longatude, speed);
The snprintf function writes onto the buffer, that is its first argument. http://www.cplusplus.com/reference/cstdio/snprintf/?kw=snprintf
Now you can use the sql string as you please.
Note that I used snprintf rather than sprintf. This is to avoid potential buffer overflows.
Also, don't use strcat so repeatedly, because that causes a Shlemiel the Painter algorithm, and every next call to strcat gets slower, because strcat has to start from the beginning and find the null terminator. See http://www.joelonsoftware.com/articles/fog0000000319.html for more info.

How do I print a Rust floating-point number with all available precision?

I am implementing the CORDIC algorithm for the sin trigonometric function. In order to do this, I need to hardcode/calculate a bunch of arctangent values. Right now my function seems to work (as validated by Wolfram Alpha) to the precision that is printed, but I would like to be able to print all 32 bits of precision of my f32. How may I do that?
fn generate_table() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
let num_bits: uint = 32;
let num_elms: uint = num_bits;
let mul: uint = 1 << (num_bits - 2);
println!("Cordic sin in rust");
println!("num bits {}", num_bits);
println!("pi is {}", pi);
println!("k1 is {}", k1);
let shift: f32 = 2.0;
for ii in range(0, num_bits) {
let ipow: f32 = 1.0 / shift.powi(ii as i32);
let cur: f32 = ipow.atan();
println!("table values {}", cur);
}
}
Use the precision format specifier; a . followed by the number of decimal points of precision you'd like to see:
fn main() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
println!("pi is {:.32}", pi);
println!("k1 is {:.32}", k1);
}
I chose 32, which is more than the number of decimal points in either of these f32s.
pi is 3.14159274101257324218750000000000
k1 is 0.60725295543670654296875000000000
Note that the values no longer match up; floating point values are difficult! As mentioned in a comment, you may wish to print as hexadecimal or even use your literals as hexadecimal.
Using the precision format specifier is the correct answer, but to print all available precision, simply refrain from specifying the number of digits to display:
// prints 1
println!("{:.}", 1_f64);
// prints 0.000000000000000000000000123
println!("{:.}", 0.000000000000000000000000123_f64);
This way, you will not truncate values nor will you have to trim excess zeros, and the display will be correct for all values, regardless of whether they are very large or very small.
Playground example
For completeness, the precision format specifier also supports a specifying a fixed precision (as per the accepted answer):
// prints 1.0000
println!("{:.4}", 1_f64);
as well as a precision specified at runtime (does not need to be const, of course):
// prints 1.00
const PRECISION: usize = 2;
println!("{:.*}", PRECISION, 1_f64); // precision specifier immediately precedes positional argument
This answer was written for Rust 0.12.0 and doesn't apply to Rust 1.x.
You can use the to_string function in std::f32 (not to be confused with the to_string method):
fn main() {
println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(1) }));
println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(16) }));
println!("{}", std::f32::to_string(std::f32::MIN_POS_VALUE));
println!("{}", std::f32::to_string(std::f32::MAX_VALUE));
println!("{}", std::f32::to_string(std::f32::consts::PI));
}
Output:
0.00000000000000000000000000000000000000000000140129852294921875
0.000000000000000000000000000000000000000000022420775890350341796875
0.000000000000000000000000000000000000011754944324493408203125
340282368002860660002286082464244022240
3.1415927410125732421875
This answer was written for Rust 0.12.0 and doesn't apply to Rust 1.x.
You can use std::f32::to_string to print all the digits.
use std::f32;
fn main() {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
println!("pi is {}", f32::to_string(pi));
println!("k1 is {}", f32::to_string(k1));
}
Output:
pi is 3.1415927410125732421875
k1 is 0.607252979278564453125
To trim trailing zeros and dots, you can do:
println!(
"number = {}",
format!("{:.2}", x).trim_end_matches(['.', '0'])
);
Examples:
input
output
3.359
3.36
3.3
3.3
3.0
3
IMHO there is no way around the bigdecimal crate, if you want to store floating-point numbers with high precision:
use bigdecimal::BigDecimal;
fn main() {
let pi = BigDecimal::parse_bytes(b"3.1415926536897932384626", 10);
let k1 = BigDecimal::parse_bytes(b"0.6072529350088812561694", 10); // 1/k
println!("pi is {pi:?}");
println!("k1 is {k1:?}");
}
gets:
pi is Some(BigDecimal("3.1415926536897932384626"))
k1 is Some(BigDecimal("0.6072529350088812561694"))

Stange behavior with my C string reverse function

I'm just an amateur programmer...
And when reading, for the second time, and more than two years apart, kochan's "Programming in Objective-C", now the 6th ed., reaching the pointer chapter i tried to revive the old days when i started programming with C...
So, i tried to program a reverse C string function, using char pointers...
At the end i got the desired result, but... got also a very strange behavior, i cannot explain with my little programming experience...
First the code:
This is a .m file,
#import <Foundation/Foundation.h>
#import "*pathToFolder*/NSPrint.m"
int main(int argc, char const *argv[])
{
#autoreleasepool
{
char * reverseString(char * str);
char *ch;
if (argc < 2)
{
NSPrint(#"No word typed in the command line!");
return 1;
}
NSPrint(#"Reversing arguments:");
for (int i = 1; argv[i]; i++)
{
ch = reverseString(argv[i]);
printf("%s\n", ch);
//NSPrint(#"%s - %s", argv[i], ch);
}
}
return 0;
}
char * reverseString(char * str)
{
int size = 0;
for ( ; *(str + size) != '\0'; size++) ;
//printf("Size: %i\n", size);
char result[size + 1];
int i = 0;
for (size-- ; size >= 0; size--, i++)
{
result[i] = *(str + size);
//printf("%c, %c\n", result[i], *(str + size));
}
result[i] = '\0';
//printf("result location: %lu\n", result);
//printf("%s\n", result);
return result;
}
Second some notes:
This code is compiled in a MacBook Pro, with MAC OS X Maverick, with CLANG (clang -fobjc-arc $file_name -o $file_name_base)
That NSPrint is just a wrapper for printf to print a NSString constructed with stringWithFormat:arguments:
And third the strange behavior:
If I uncomment all those commented printf declarations, everything work just fine, i.e., all printf functions print what they have to print, including the last printf inside main function.
If I uncomment one, and just one, randomly chosen, of those comment printf functions, again everything work just fine, and I got the correct printf results, including the last printf inside main function.
If I leave all those commented printf functions as they are, I GOT ONLY BLANK LINES with the last printf inside main block, and one black line for each argument passed...
Worst, if I use that NSPrint function inside main, instead of the printf one, I get the desired result :!
Can anyone bring some light here please :)
You're returning a local array, that goes out of scope as the function exits. Dereferencing that memory causes undefined behavior.
You are returning a pointer to a local variable of the function that was called. When that function returns, the memory for the local variable becomes invalid, and the pointer returned is rubbish.

Math with mixed variable data types

I am calculating a percent complete with variables of mixed data types.
int incompleteCritical = 12;
int total = 24;
float progress = 0;
NSLog(#"Incomplete Total: %d", incompleteCritical);
NSLog(#"Total Total: %d", total);
if (total > 0) {
progress = ((float)incompleteCritical/(float)total)*100;
NSLog(#"Progress: %d", progress);
}
The console output is as follows:
2011-01-11 10:02:59.993 [18570:207] Incomplete Total: 12
2011-01-11 10:02:59.993 [18570:207] Total Total: 24
2011-01-11 10:02:59.994 [18570:207] Progress: 0
Why is Progress not returning "50"?
You're using the wrong format string in your NSLog statement. %d is used for integers. You need to use %f when you log floating point numbers. (There are extra parameters to use to limit the number of decimal places, etc.)