У меня есть текстовый файл с заданным форматом:чтение форматированный текстовый файл в массив
2078.62 5.69982 -0.17815 -0.04732
5234.95 8.40361 0.04028 0.10852
2143.66 5.35245 0.10747 -0.11584
7216.99 2.93732 -0.18327 -0.20545
1687.24 3.37211 0.14195 -0.14865
2065.23 34.0188 0.1828 0.21199
2664.57 2.91035 0.19513 0.35112
7815.15 9.48227 -0.11522 0.19523
5166.16 5.12382 -0.29997 -0.40592
6777.11 5.53529 -0.37287 -0.43299
4596.48 1.51918 -0.33986 0.09597
6720.56 15.4161 -0.00158 -0.0433
2652.65 5.51849 0.41896 -0.61039
Я написал следующие функции для чтения файла
Прочитайте количество строк
unsigned int getnumline(const char *sn){
unsigned int n;
char lcstring[LCLENGTH];
FILE *lcpipe;
char buff[512];
snprintf(lcstring, LCLENGTH,
"wc -l %s | cut -d ' ' -f1", sn);
lcpipe = popen(lcstring, "r");
if (lcpipe == NULL)
exit_failure("popen: ");
while(fgets(buff, sizeof(buff), lcpipe)!=NULL){
n=atoi(buff);
}
pclose(lcpipe);
printf("Number of lines in the input file: %d\n", n);
return n;
}
Прочитайте текстовый файл
double **callocmatrix(unsigned int m, unsigned int n) {
double **matrix;
unsigned int i;
matrix = (double **)calloc(m, sizeof(double *));
if (!matrix)
return NULL;
matrix[0] = (double *)calloc(m*n, sizeof(double));
if (!matrix[0])
return NULL;
for (i = 1; i < m; i += 1)
matrix[i] = matrix[i-1] + n;
return matrix;
}
void freematrix(double **matrix) {
free((void *)matrix[0]);
}
double **ellcat;
ngal = getnumline(sname);
ellcat = callocmatrix(ngal, 4);
void readcat(double **ellcat, unsigned int catlen, const char *sn) {
unsigned int i;
FILE *fp=fopen(sn,"r");
if(fp == NULL)
{
printf("Error in opening file\n");
exit(0);
}
for (i=0 ; i< catlen ; i++)
{
fscanf(fp, "%lf %lf %lf %lf", &ellcat[i][0], &ellcat[i][1], &ellcat[i][2], &ellcat[i][3]);
}
for (i=0 ; i< catlen ; i++)
{
printf("x = %lf, y = %lf, e1 = %lf, e2 = %lf\n", &ellcat[i][0], &ellcat[i][1], &ellcat[i][2], &ellcat[i][3]);
}
fclose(fp);
}
Но ellcat
компоненты пустые
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
x = 0.000000, y = 0.000000, e1 = 0.000000, e2 = 0.000000
Я не могу понять, что проблема с моей readcat
функции.
P.S. Должен упомянуть, что я новичок в отношении языка C.
Начните поиск результата, возвращенного 'fscanf': он вернет количество элементов, которые будут правильно прочитаны. – Evert
Просьба представить декларацию и инициализацию 'ellcat' в вашем вопросе. – Evert
@Evert Я получаю 'catlen', используя функцию' getnumline'. – Dalek