Michal, 1) There is a problem in getfloats() function. cc[0] is assigned several times but cc[1] is never. In C/C++, local variable is not initialized unless you explicitly initialize. char cc1[2]; // global variable. Always initialized is '\0\0' void f() { char cc2[2]; // local variable. Not initialized. Unknown value cc2[0]='a'; // cc2 is 'a' + unknown value } You were just lucky that cc happend to be initialized to '\0\0'. It can cause problem in any compiler and any environment. 2) Another point that might cause problem is fgets. I think it is safer to replace '\n' at the end of fgets read string to 0. fgets(tmpstr,SLEN,infp); char *p=strchr(tmpstr,'\n'); if(p) *p = 0; Masaharu Goto ---------------------------------------------------------------------- The following code crashes most of the time with the segmentation violation in root 2.20/06 for SunOS5.4 on Sparc. But when compiled with gcc it works fine. It works also when instead calling a function I parse a string inside main macro. Thanks for any hints. Regards Michal Lijowski #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> // ------------------------------------------------------------------------- int getfloats(char *tmpstr, float *aa) // extracts up to 10 floating point numbers from a string { int SLEN = 40; char cc[2], str1[SLEN]; int sl = strlen(tmpstr); printf("%4d %s", sl, tmpstr); cc[0] = tmpstr[0]; int jj = 0; int ii = 0; while ( (ii < 10) && (jj < sl) ) { str1[0] = '\0'; while ( (cc[0] != ' ') && (jj < sl) ) { strncat(str1, cc, 1); jj++; cc[0] = tmpstr[jj]; } aa[ii] = atof(str1); ii++; // skip white spaces while ( (cc[0] == ' ') && (jj < sl) ) { jj++; cc[0] = tmpstr[jj]; } } return ii; } // --------------------------------------------------------------------- void test_read() { char infile[200]; float aa[10]; int SLEN = 80, nn; char tmpstr[SLEN], str1[20], cc[2]; sprintf(infile, "tmp.dat"); printf("%s\n", infile); FILE *infp = fopen(infile, "r"); if (infp == NULL) { printf("test_read2b can't open %s\n", infile); exit(1); } int npts = 0; // loop until EOF while (fgets(tmpstr, SLEN, infp) != NULL) { printf(" %s", tmpstr); nn = getfloats(tmpstr, aa); for (int ii = 0; ii < nn; ii++) { printf(" %f ", aa[ii]); } printf("\n"); npts++; } fclose(infp); }
This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:43:28 MET