Append Array from different .txt file - arrays

I have 63 .txt file with 26 headers lines and then 19 columns of float data.
I would like to read all the files and store (in row) the first 6 columns of the .txt files (x,y,z,u,v,w). Then for each .txt file I would like to append these data in a new row.
This is the code that I did but after the first j (j=1) then the script crash because the sizes of the arrays are not the same, indeed for some reasons during the first iteration it is skipping not 26 but 52 lines (so also the first 26 of numbers that I want), while in the second is (in a correct way skiiping only 26 headers line).
inpDir = "\\ftac\Folder\CD";
files = dir(fullfile(inpDir, '*.txt'));
n_file = size(files,1);
for j=1:n_file
fid = fopen(files(j).name, 'r');
data = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f', 'HeaderLines', 26, 'Delimiter',' ');
fclose(fid);
x(j, :) = data{1}'; % x coordinate
y(j, :) = data{2}'; % y coordinate
z(j, :) = data{3}'; % y coordinate
u(j, :) = data{4}';% u velocity
v(j, :) = data{5}'; % v velocity
w(j, :) = data{6}'; % w velocity
end
How can I solve this issue? Thanks in advance

Related

How to read data into array in MATLAB?

I'm writing a code to solve Ax=b using MATLAB's x=A\B. I believe my problem lies within getting the data from the files into the array. Right now, the solution vector is coming out to be a load of 0's
The matrices I'm using have 10 rows respectively. They are aligned correctly in the text files.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
fileID = fopen('a_matrix.txt', 'r');
formatSpec = '%d %f';
sizeA = [10 Inf];
A = load('b_matrix.txt');
A = A'
file2ID = fopen('b_matrix.txt','r');
formatSpec2 = '%d %f';
sizeB = [10 Inf];
b = load('b_matrix.txt');
fclose(file2ID);
b = b'
% solve the linear system
x = A\b;
% write output data on file
dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);
I answered my own question but I felt the need to share in case anyone else has similar troubles.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
f = textread('a_matrix.txt', '%f');
vals = reshape(f, 11, []).';
A = vals(:,1:10);
b = vals(:,11);
% solve the linear system
x = A\b;
% write output data on file
dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);
I ended up combining the 'a' and 'b' matrix into a single text file for simplicity. Now, MATLAB reads data in by columns, so it is necessary to use 'reshape' in order to fit the data within the array correctly. Then, I filtered out the information from the single matrix by columns, using the 'vals' function as seen in my code. The 'A' matrix is essentially all numbers in columns 1 through 10, while the 'B' matrix is the 11th (and final) column.
Using MATLAB's x=A\b function, I was able to solve the linear system of equations.

Length of the intercept from intersection of a line with a cylinder (ring)

I have some sources with coordinates (xn, yn, zn) w.r.t a center C of a ring and unit vectors (ns_ux, ns_uy, ns_uz) along my line of sight. I want to calculate whether these sources pass through a cylinder of inner and outer radius 9.5 and 10.5 units, respectively. If they intersect this cylinder (or I call it ring, sometimes), then I would like to calculate the length of this intercept. My position is outside of this ring and there are sources which lie beyond the center C on the other side. These sources, therefore will pass through this ring twice. This picture should help visualize this problem.
#define PI 3.142
int main(){
int k,number=200;
float r_min=9.50000;
float r_max=10.500000;
float step=0.3;
float z_c = 3.0;
float ns_ux[number],ns_uy[number],ns_uz[number],xn[number], yn[number],zn[number],l[number],b[number],ns[number],x_comp,y_comp,z_comp,radial;
FILE* val= NULL;
val=fopen("novae_uniform_unitvectors.txt", "r");
for(k=0;k<=(number-1);k++){
fscanf(val,"%f %f %f %f %f %f %f %f %f", &xn[k], &yn[k], &zn[k], &ns_ux[k], &ns_uy[k], &ns_uz[k], &l[k], &b[k], &ns[k]);
float u=0.;
for (u=0.;u<=30.;u=u+step){
x_comp=xn[k]+u*ns_ux[k];
vector addition : calculating the x_comp w.r.t the center C when stepped by 'u' units along my l.o.s.
y_comp=yn[k]+u*ns_uy[k];
radial=pow((x_comp*x_comp+y_comp*y_comp),0.5);
if (radial >=r_min && radial <=r_max){
z_comp=zn[k]+u*ns_uz[k];
checking if the height is consistent with the ring's height
if(z_comp >=-z_c && z_comp <= z_c)
printf("%f\t%f\t%f\t%f\n",l[k],u, z_comp, radial);
}
}
}
return 0.;
}
This 'radial' values gives me a list of points where my line of sight intersects with the ring. But, I require only the end points to calculate the length of the intercept on the ring.
e.g. in the case listed below, my l.o.s. passes through the ring at I and then comes off at II. Then it keeps going until it hits the ring again at III and then come out of it at IV. I need to store only I, II , III and IV points in my file. How would I be able to do it ?
longitude..........u........ z_comp........radial
121.890999 0.100000 0.016025 9.561846 I
121.890999 0.200000 0.038453 9.538050
121.890999 0.300000 0.060881 9.515191 II
121.890999 4.799998 1.070159 9.518372 III
121.890999 4.899998 1.092587 9.541364
121.890999 4.999998 1.115016 9.565292
...... skipping to save space........
121.890999 7.399995 1.653297 10.400277
121.890999 7.499995 1.675725 10.444989
121.890999 7.599995 1.698153 10.490416 IV
Figured out a way to store only the final and initial values by using a boolean operator as follows (continued from the code in the question) :
define bool change = true;
...(rest of the program)...
if(radial >= r_min && radial <= r_max) {
z_comp = zn[k] + u * ns_uz[k];
if (z_comp >= -z_c && z_comp <= z_c)
if (change) {
printf("%f\t%f\t%f\t%f\t", l[k], b[k], ns[k], radial[i]);
change = !change;
}
} else { // if the condition of radial and z_comp is not met
if (!change) {
fprintf(fp, "%f\n", radial[i - 1]);
change = !change;
}
}
This would store only the first and the last values of the radial component (i.e. the end points of the intercept of the line of sight vector on the ring)

The output of ceil() and floor() in C language is odd

I am doing my homework to realize a C programe and during my work there is one step that I need to get the interger part of the double type numbers. So I choose ceil() or floor() in to realize this. But the output is unpredictable and far from expected.
The whole program is the following :
/*
************************************************************************
Includes
************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <time.h>
#include <math.h>
/* Solvent Particle Propersities*/
typedef struct
{
double vx,vy,rx,ry ; /* velocity AND position */
double cell; /* index of grid */
}solvent_p;
/* Cell Propersities*/
typedef struct
{
double vcm_x,vcm_y ; /* center of mass velocity */
int number; /* number of solvent in the cell */
double roation_angle; /* roation_angle of the cell */
}cell_p;
/* periodic boundary condition judging and adjusting fuction PBC */
void PBC(solvent_p *sol)
{
double L = 20.0; // box size 20
if(sol->rx >20) sol->rx=sol->rx-L;
if(sol->rx < 0) sol->rx=sol->rx+L;
if(sol->ry >20) sol->ry=sol->ry-L;
if(sol->ry < 0) sol->ry=sol->ry+L;
}
int main(int argc, char **argv)
{
// Randome setup generates random numbers from GSL functions
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
gsl_rng_default_seed = ((unsigned long)(time(NULL))); //设seed值为当前时间
r = gsl_rng_alloc (T);
solvent_p solvent[4000];
int i,j,k,index=0;
cell_p grid[400];
double alpha=90.0; //roation angle
/* Iniinitializing solvent
* All vx=0
* half vy = sqrt(3) and half vy=-sqrt(3) to make momentum zero and another requirement is the overall energy is 6000 equals energy of temperature=1 with 4000 solvent 3NkT/2 ,assuming mass of solvent = 1 ,which is all a test quantity
* rx and ry are random number generated by GSL library
* cell=20*(ry+rx) is an index of which cell the solvent is in
*/
for(i=0;i<=3999;i++)
{
solvent[i].vx=0.0;
if(i<=1999)
solvent[i].vy=sqrt(3);
else
solvent[i].vy=-sqrt(3);
solvent[i].rx =20.0 * gsl_rng_uniform_pos(r);
solvent[i].ry =20.0 * gsl_rng_uniform_pos(r);
//printf("%f \t %f \n",solvent[i].rx,solvent[i].ry);
solvent[i].cell=20*(floor(solvent[i].ry))+floor(solvent[i].rx)+1;
}
// grid setting up
for (i=0;i<=399;i++)
{
grid[i].vcm_x=0;
grid[i].vcm_y=0;
grid[i].number=0;
grid[i].roation_angle=0.0;
}
/* Begining Simulation Work
*
* Fist process is preparing the system to equilibrium for 10000 processes
*
* the whole process involving two steps steaming and collision and the two steps are conducted one by one in our simulation
* time duration for steaming is 0.1 which is assigned for Molecular Dynamics and time duration for collision is ignored
*
*
*/
for(i=0;i<=9999;i++)
{
double temp;
double delta_t_MD=0.1; //time step
temp=gsl_rng_uniform_pos(r);
double rand_rx = (temp < 0.5) ? temp : ((-1) * temp ); // randomshift rx;
temp=gsl_rng_uniform_pos(r);
double rand_ry = (temp < 0.5) ? temp : ((-1) * temp ); // randomshift ry
//steaming
for(j=0;j<=3999;j++)
{
//printf("%d \n",j);
printf("1 :%d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
solvent[j].rx=solvent[j].rx+solvent[j].vx * delta_t_MD;
solvent[j].ry=solvent[j].ry+solvent[j].vy * delta_t_MD;
printf("2: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
//randomshift
solvent[j].rx=solvent[j].rx+rand_rx;
solvent[j].ry=solvent[j].ry+rand_ry;
printf("3: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
// periodic boundary condition
PBC(&solvent[j]);
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry);
solvent[j].cell=20*(ceil(solvent[j].ry)-1)+ceil(solvent[j].rx);
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[j].ry,ceil(solvent[j].rx),ceil(solvent[j].ry));
index = (int)(solvent[j].cell);
//printf("%d \t %d \t %f \t %f \t %f \n",j,index,solvent[j].cell,ceil(solvent[j].rx),ceil(solvent[j].ry));
if ((index>=0) &&(index<=400))
{
grid[index].vcm_x=grid[index].vcm_x+solvent[i].vx;
grid[index].vcm_y=grid[index].vcm_y+solvent[i].vy;
grid[index].number=grid[index].number+1;
}
}
// caculating vcm
for (k=0;k<=399;k++)
{
if (grid[k].number >= 1)
{
grid[k].vcm_x=grid[k].vcm_x/grid[k].number;
grid[k].vcm_y=grid[k].vcm_y/grid[k].number;
}
double temp;
temp=gsl_rng_uniform_pos(r);
grid[k].roation_angle = (temp < 0.5) ? alpha : ((-1) * alpha );
}
//collsion
}
gsl_rng_free (r); // free RNG
return 0;
}
Sorry it is some extent long so I did not put in first.And something did not finished but the program framework is set up.
my programe is like this:
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
solvent[j].cell=20*(floor(solvent[j].ry))+floor(solvent[j].rx)+1;
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,floor(solvent[j].rx),floor(solvent[j].ry));
And although something as I wanted something more is wrong and below is I choose some parts of the output:
4: 3993 3.851240 17.047031
5: 3993 3.851240 17.047031 3.000000 9.000000
although floor(solvent[j].rx) is right but floor(solvent[j].ry) is totally wrong.
And the final result of my program is
Segmentation fault (core dumped)
------------------
(program exited with code: 139)
How to fix this one? Is there anything I use was wrong?
And to further test the problem I tried ceil() function in and the program and result is like this
program:
printf("4: %d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
solvent[j].cell=20*(ceil(solvent[j].ry)-1)+ceil(solvent[j].rx);
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,ceil(solvent[j].rx),ceil(solvent[j].ry));
result:
2: 3999 14.571205 2.837654
4: 3999 14.571205 2.837654
5: 3999 14.571205 2.837654 15.000000 15.000000
So use the nearest output as an example to illustrate my desire result is:
a= 14.571205, ceil(a)=15.00
b= 2.837654 , ceil(b)=3.00 not the 15.000 in the output
And the problem worsening is that when I just use a and b to test ceil() everything seems perfect:
program:
#include <stdio.h>
#include <math.h>
int main()
{
double a= 14.571205;
double b= 2.837654 ;
printf("%f \t %f \n",ceil(a),ceil(b));
return 0;
}
output:
15.000000 3.000000
I am using GCC in Linux Ubuntu.
==============================================================================
The problem has been solved.
The real fatal problem is here
if ((index>=0) &&(index<=400))
{
grid[index].vcm_x=grid[index].vcm_x+solvent[i].vx;
grid[index].vcm_y=grid[index].vcm_y+solvent[i].vy;
grid[index].number=grid[index].number+1;
}
}
Both solvent[i].vy and solvent[i].vx should be changed i for j.
Just as #Jon and #Blckknght #Eric Lippert have pointed out.
And I obvious get in the wrong trap and mislead #ouah and #Blckknght and In fact, the output sentences do have problem but they do not caused the prorame to crash only the out of boundary will do that.
Thank you ALL!
And I do like to share Eric Lippert 's comment which is powerful and insightful:
More generally, the problem you have is called "select isn't broken" by experienced programmers. That is, you have done something completely wrong, you cannot figure out what you did wrong, and so you conclude that a piece of basic, easy infrastructure written by experts and tested extensively is wrong. I assure you, floor and ceil do exactly what they are supposed to do. They are not wrong. The problem lies somewhere in your code, not in the standard library. – Eric Lippert
Your array is declared as:
solvent_p solvent[4000];
but you have this loop:
for(i=0;i<=9999;i++)
with this function call inside:
printf("1 :%d \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry);
which means you are accessing out-of-bounds array elements.
EDIT:
OP test case has been edited to fix the out-of-bound accesses.
My second suggestion is to check index value (which is used to index grid array) never exceeds the number of elements of grid array after this assignment: index = (int)(solvent[j].cell).
I'm pretty sure the issue is with the indexes you're using. In the statement in question:
printf("5: %d \t %f \t %f \t %f \t %f \n",j,solvent[j].rx,solvent[i].ry,floor(solvent[j].rx),floor(solvent[j].ry));
you are printing the ry value of solvent[i] but the floor of the ry value of solvent[j]. I suspect that you want to be using the same index in both places (though I'm not sure which index you want).

Parsing Integer and Float Values of a Text File with sscanf

I want to parse such a file with these fields into integer and float variables,I tried to do this using fscanf,strtok,sscanf. But none of them works!
Some lines of the file :
fed18 5.7 12.7 144997 8087 267345 100776
fedora18 24.9 25.3 253566 10501 126282 118157
fed18 5.9 12.7 145005 8094 267345 100785
fedora18 23.3 25.3 253576 10507 126282 118169
fed18 6.2 12.7 145013 8100 267345 100789
Running the following code returns wrong values! I don't know what's the problem as I search, everybody use such this code and it works properly for them!
while(fgets(str,512,fp)!= NULL)//read file line by line
{
char *tokenstring = str;
uint64_t netrx,nettx,vbd_rd,vbd_wr;
double cpu, mem;
char a[10],b[10],c[10],d[10],e[10],f[10],g[10];
sscanf(tokenstring, "%s ,%[^' '],%[^' '],%[^' '],%[^' '],%[^' '],%[^' ']",g, a, b, c, d, e, f);
cpu = atof(a);
mem = atof(b);
nettx = atoi(c);
netrx = atoi(d);
vbd_rd = atoi(e);
vbd_wr = atoi(f);
printf("%s %f %f %ld %ld %ld %ld\n",g,cpu,mem,netrx,nettx,vbd_rd,vbd_wr);
}
fclose(fp);
Here is the output:
fed18 38.000000 1.000000 0 0 0 0
fedora18 38.000000 1.000000 0 0 0 0
fed18 38.000000 1.000000 0 0 0 0
fedora18 38.000000 1.000000 0 0 0 0
fed18 38.000000 1.000000 0 0 0 0
I edited the original text file with a bash script and using awk ,....
The original lines were in this format:
fed18 --b--- 3616 6.3 1052640 12.7 1052672 12.7 3 1 125864 6023 1 0 254349 93082 7412662 4730752 0
fedora18 --b--- 4711 2.4 2101216 25.3 2101248 25.3 3 1 249151 8636 1 0 126083 113505 3306934 5992656 0
I selected some columns using a bash script.
maybe this caused the problem!
I commented the lines of using function atoi or atof but still output wrong values.
If you always expect a single space between arguments you can simply your format string and obviate the need for atoi, atof:
while(fgets(str,512,fp)!= NULL)//read file line by line
{
char *tokenstring = str;
uint64_t netrx,nettx,vbd_rd,vbd_wr;
char g[10];
double cpu, mem;
long int c, d, e, f;
sscanf(tokenstring, "%s %lf %lf %lu %lu %lu %lu", g, &cpu, &mem, &nettx, &netrx, &vbd_rd, &vbd_wr);
printf("%s %f %f %ld %ld %ld %ld\n",g,cpu,mem,netrx,nettx,vbd_rd,vbd_wr);
}
fclose(fp);
Your format string contains commas that don't exist in the input. That said, you should use %lf to parse floating point numbers into double and %lu to parse into uint64_t.
Note that you might run into trouble when the current locale isn't English because that influences which character C expects as a decimal point. Use setlocale(LC_NUMERIC, "C"); to fix that.
scanf is designed to parse numbers so there is no need to use atoi, so just use sscanf with proper parameters
int result = sscanf(tokenstring, "%s %lf %lf %lld %lld %lld %lld",g, &cpu, &mem, &netrx, &netrx, &vbd_rd, &vbd_wr);
assert( result == 7 ) ;

Why is stack smashing occuring in this C code?

I apologize in advance for my lack of knowledge regarding stack smashing in C.
I'm on ubuntu 12.04 editing with Code::Blocks.
I have written a simple C program that causes stack smashing, but internet searches have turned up little useful advice as to why this is happening.
Example C code:
#include<stdio.h>
struct point3
{float x, y, z;};
struct quadPolygon
{struct point3 vert1, vert2, vert3, vert4;};
int writeLine(const char * objString)
{FILE *file; file = fopen("aPlane.obj","a+"); fprintf(file,"%s",objString); fclose(file); return 0;};
int writeOBJ(struct quadPolygon myPoly)
{
char objString[] = "# plane def\n"; writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert1.x, myPoly.vert1.y, myPoly.vert1.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert2.x, myPoly.vert2.y, myPoly.vert2.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert3.x, myPoly.vert3.y, myPoly.vert3.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert4.x, myPoly.vert4.y, myPoly.vert4.z); writeLine(objString);
char objStringSmooth[] = "s off\n"; writeLine(objStringSmooth);
char objStringFace[] = "f 1 2 3 4\n"; writeLine(objStringFace);
return 0;
};
int main()
{
struct quadPolygon myPoly1 =
{
.vert1.x=1.0, .vert1.y=-1.0, .vert1.z=0.0,
.vert2.x=1.0, .vert2.y=1.0, .vert2.z=0.0,
.vert3.x=-1.0, .vert3.y=1.0, .vert3.z=0.0,
.vert4.x=-1.0, .vert4.y=-1.0, .vert4.z=0.0
};
writeOBJ(myPoly1);
return 0;
};
Why is the stack smashing and how could I change my code to avoid this? Is this related to using pointers incorrectly in the code above? I'm a little new to C as you can probably tell, but have some programming experience with other languages.
I have read that "Stack Smashing is actually a protection mechanism used by gcc to detect buffer overflow attacks" and "It means that you wrote to some variables on the stack in an illegal way, most likely as the result of a Buffer overflow".
Thank you for any responses/answers.
Update -
Based on Evan's comment, here is revised code that works. Perhaps this may help someone else.
#include<stdio.h>
struct point3
{float x, y, z;};
struct quadPolygon
{struct point3 vert1, vert2, vert3, vert4;};
int writeOBJ(struct quadPolygon myPoly)
{
FILE *file; file = fopen("aPlane.obj","a+");
fprintf(file,"%s","# plane def\n");
char objString[128];
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert1.x, myPoly.vert1.y, myPoly.vert1.z);
fprintf(file,"%s",objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert2.x, myPoly.vert2.y, myPoly.vert2.z);
fprintf(file,"%s",objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert3.x, myPoly.vert3.y, myPoly.vert3.z);
fprintf(file,"%s",objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert4.x, myPoly.vert4.y, myPoly.vert4.z);
fprintf(file,"%s",objString);
char objStringSmooth[] = "s off\n";
fprintf(file,"%s",objStringSmooth);
char objStringFace[] = "f 1 2 3 4\n";
fprintf(file,"%s",objStringFace);
fclose(file);
return 0;
};
int main()
{
struct quadPolygon myPoly1 =
{
.vert1.x=1.0, .vert1.y=-1.0, .vert1.z=0.0,
.vert2.x=1.0, .vert2.y=1.0, .vert2.z=0.0,
.vert3.x=-1.0, .vert3.y=1.0, .vert3.z=0.0,
.vert4.x=-1.0, .vert4.y=-1.0, .vert4.z=0.0
};
writeOBJ(myPoly1);
return 0;
};
Thanks again everyone.
This is where your problem is:
char objString[] = "# plane def\n"; writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert1.x, myPoly.vert1.y, myPoly.vert1.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert2.x, myPoly.vert2.y, myPoly.vert2.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert3.x, myPoly.vert3.y, myPoly.vert3.z); writeLine(objString);
snprintf(objString, 128, "v %f %f %f \n", myPoly.vert4.x, myPoly.vert4.y, myPoly.vert4.z); writeLine(objString);
objString is an array with strlen("# plane def\n") + 1 characters of space. Then you use snprintf on that buffer passing 128 (which is WAY too large).
I would re-write it this way:
writeLine("# plane def\n");
char objString[128]
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert1.x, myPoly.vert1.y, myPoly.vert1.z); writeLine(objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert2.x, myPoly.vert2.y, myPoly.vert2.z); writeLine(objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert3.x, myPoly.vert3.y, myPoly.vert3.z); writeLine(objString);
snprintf(objString, sizeof(objString), "v %f %f %f \n", myPoly.vert4.x, myPoly.vert4.y, myPoly.vert4.z); writeLine(objString);
SIDE POINT:
Why are you opening and closing the file for every line written? That is incredibly inefficient...
Would be better to open the file once at program start, write all your lines, then close it when finished. This will also make the code simpler.
you can confirm that you are getting a valid FILE* by fopen..
by explicit check of NULL pointer.
The problem is with the following line:
char objString[] = "# plane def\n";
This only allocates just enough space for the string "# plane def\n", and later on, you write longer strings into it (using snprintf).
Since you're already using the constant value 128, how about:
char objString[128];
strcpy(objString, "# plane def\n");
writeLine(objString);
/* continue as before */
Note that strcpy can smash the stack too, so make sure the destination has enough space for whatever you're copying in.
As it is already answered by Evan Teran. But I would like to suggest few ways to detect such problems :
Try compiling using gcc -fno-stack-protector stack.c and check whether it still gives you stack smash detected.
use -g flag for gnu-debugger. As gcc -g stack.c and then gdb a.out -> run. It will stop execution where it got problem. Then you can type where in gdb to see which line of code is root of the problem.

Resources