C使用动态分配从文件中读取行和空格

时间:2018-05-09 20:46:35

标签: c dynamic-memory-allocation

我试图通过使用逆向工程过程从文件中读取矩阵。我试图做的第一部分是使用malloc或calloc创建一个文件。我使用了malloc,因为系统会提示用户输入要输入的行数或列数。我还在屏幕上打印出最终矩阵和用户定义的文件名。

我现在遇到的问题是我能够在第二部分获取文件名,但是一旦找到文件名,程序就会冻结并停止执行下一步操作。

以下是我的代码:

//preprocessors

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

//macros

#define STRING_MAX 50

//function prototypes

void printDiagonal (double ** m, int r, int c);

int main (int argc, char * argv [ ])
{
FILE * ptrIn;
FILE * ptrOut;

char inFileName [STRING_MAX];
char outFileName [STRING_MAX];

int row;
int col;

int r;
int c_temp;
int c;

char spaces;
char lines;

int i, j, k;

int ctrSpaces = 0;
int ctrLines = 0;
int ctrH = 0;
int ctrV = 0;

double matrixVals;
double ** matrixIn;
double ** matrixOut;

//get a file name first

printf ("\nEnter a file name >> ");
scanf ("%s", inFileName);

//open the file

ptrIn = fopen (inFileName, "w");

//get matrix dimensions

printf ("\nEnter the row and column sizes >> ");
scanf ("%d", &row);
scanf ("%d", &col);
printf ("\nRows >> %d\nCols >> %d\n\n", row, col);

matrixIn = (double **) malloc (row * sizeof (double *));
if (matrixIn == NULL)
{
    printf ("\nSORRY, NOT ENOUGH MEMORY!\n\n");
    exit (0);
}
for (i = 0; i < row; i ++ )
{
    matrixIn [i] = (double *) malloc (col * sizeof (double));
    if (matrixIn [i] == NULL)
    {
        printf ("\nSORRY, NOT ENOUGH MEMORY!\n\n");
        exit (0);
    }
}

//input the values into the matrix

printf ("\nEnter the values into the matrix >> \n\n");

for (i = 0; i < row; i ++)
{
    for (j = 0; j < col; j ++)
    {
        printf ("\n\nEnter [%d][%d] of [%d][%d] >> ", (i + 1), (j + 1), row, col);
        scanf ("%lf", &matrixIn [i] [j]);
    }
}

//print out the matrix

printf ("\nElements in the matrix >> \n\n");
for (i = 0; i < row; i ++)
{
    for (j = 0; j < col; j ++)
    {
        printf ("%.3lf\t", matrixIn [i][j]);
        fprintf (ptrIn, "%.3lf\t", matrixIn [i][j]);
    }
    printf ("\n");
    fprintf (ptrIn, "\n");
}
printf ("\n");
fprintf (ptrIn, "\n");

for (i = 0; i < row; i ++)
{
    free (matrixIn [i]);
}
free (matrixIn);

fclose (ptrIn);

printf ("\n-----------------------------------------------------------------------------------------------------------------\n\n");

/**------------------------------------------------------------------------------------------------------------------------------------------------------------------------------**/

//now retrieve the file by first getting user input for file name and check that the file exists

FILE_NAME:

printf ("\nEnter the name of file to access >> ");
scanf ("%s", outFileName);
printf ("\nThe name of the file is >> %s\n\n", outFileName);

//now open the file

ptrOut = fopen (outFileName, "r");

//check that the file exists

if (ptrOut == NULL)
{
    printf ("\nSORRY, THE FILE DOES NOT EXIST. PLEASE ENTER A VALID FILE NAME.\n\n");
    goto FILE_NAME;
}

//get the number of rows and columns

for (lines = fgetc (ptrOut); lines != EOF; lines == fgetc (ptrOut))
{
    if (lines == '\t' || lines == ' ')
    {
        ctrLines ++;
        if (lines == EOF)
        {
            break;
        }
    }
}

c_temp = ctrLines;

for (spaces = fgetc (ptrOut); spaces != EOF; spaces = fgetc(ptrOut))
{
    if (spaces == '\n')
    {
        ctrSpaces ++;
        if (spaces == EOF)
        {
            break;
        }
    }
}

r = ctrSpaces;

//total number of rows is:

c = c_temp / r;

printf ("\nNumber of rows >> %d\n\nNumber of columns >> %d\n\n", r, c);

matrixOut = (double **) malloc (r * sizeof (double *));
if (matrixOut == NULL)
{
    printf ("\nSorry, not enough memory!\n\n");
    exit (0);
}

for (i = 0; i < r; i ++)
{
    matrixOut [i] = (double *) malloc (c * sizeof (double));
    if (matrixOut [i] == NULL)
    {
        printf ("\nSorry, not enough memory!\n\n");
        exit (0);
    }
}

for (i = 0; i < r; i ++)
{
    free (matrixOut [i]);
}
free(matrixOut);

fclose (ptrOut);

//reopen the file and get the information from the file

ptrOut = fopen (outFileName, "r");

matrixOut = (double **) malloc (c * sizeof (double *));

for (i = 0; i < r; i++)
{
    matrixOut [i] = (double *) malloc (c * sizeof (double));
}

printf ("\nMatrix from File %s of dimensions %d X %d >>\n\n", outFileName, r, c);

for (i = 0; i < r; i ++)
{
    for (j = 0; j < c; j ++)
    {
        fscanf (ptrOut, "%lf", &matrixVals);
        matrixOut [i] [j] = matrixVals;
        printf ("%.3lf\t", matrixOut [i] [j]);
    }
    printf ("\n");
}
printf ("\n");

for (i = 0; i < r; i ++)
{
    free (matrixOut [i]);
}
free(matrixOut);

fclose (ptrOut);

return (0);
}

这是我的输出: https://1drv.ms/u/s!AqM2tvkVzTumh58mcliiAUKD9Uu7Ew

澄清我的问题。

由于

1 个答案:

答案 0 :(得分:0)

我终于感谢user3629249。我只需将读取行号和读取行号的两个操作分开。对于行号,我不得不从总行数中减去1,因为它在\0之后添加了额外的EOL

这是我的最终代码(以及我最初没有提到的功能,用于打印主要的&#34;次要&#34;方形矩阵的对角线。

 //preprocessors

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

//macros

#define STRING_MAX 50

//function prototypes

void printMajorDiagonal (double ** m, int r, int c);
void printMinorDiagonal (double ** m, int r, int c);

int main (int argc, char * argv [ ])
{
FILE * ptrIn;
FILE * ptrOut;

char inFileName [STRING_MAX];
char outFileName [STRING_MAX];

int row;
int col;

int r;
int c_temp;
int c;

char spaces;
char lines;
char ch;

int i, j, k;

int ctrSpaces = 0;
int ctrLines = 0;
int ctrH = 0;
int ctrV = 0;
int charCount = 0;
int lineCount = 0;

double matrixVals;
double ** matrixIn;
double ** matrixOut;

//get a file name first

printf ("\nEnter a file name >> ");
scanf ("%s", inFileName);

//open the file

ptrIn = fopen (inFileName, "w");

//get matrix dimensions

printf ("\nEnter the row and column sizes >> ");
scanf ("%d", &row);
scanf ("%d", &col);
printf ("\nRows >> %d\nCols >> %d\n\n", row, col);

matrixIn = (double **) malloc (row * sizeof (double *));
if (matrixIn == NULL)
{
    printf ("\nSORRY, NOT ENOUGH MEMORY!\n\n");
    exit (0);
}
for (i = 0; i < row; i ++ )
{
    matrixIn [i] = (double *) malloc (col * sizeof (double));
    if (matrixIn [i] == NULL)
    {
        printf ("\nSORRY, NOT ENOUGH MEMORY!\n\n");
        exit (0);
    }
}

//input the values into the matrix

printf ("\nEnter the values into the matrix >> \n\n");

for (i = 0; i < row; i ++)
{
    for (j = 0; j < col; j ++)
    {
        printf ("\n\nEnter [%d][%d] of [%d][%d] >> ", (i + 1), (j + 1), row, col);
        scanf ("%lf", &matrixIn [i] [j]);
    }
}

//print out the matrix

printf ("\nElements in the matrix >> \n\n");
for (i = 0; i < row; i ++)
{
    for (j = 0; j < col; j ++)
    {
        printf ("%.3lf\t", matrixIn [i][j]);
        fprintf (ptrIn, "%.3lf\t", matrixIn [i][j]);
    }
    printf ("\n");
    fprintf (ptrIn, "\n");
}
printf ("\n");
fprintf (ptrIn, "\n");

for (i = 0; i < row; i ++)
{
    free (matrixIn [i]);
}
free (matrixIn);

fclose (ptrIn);

printf ("\n-----------------------------------------------------------------------------------------------------------------\n\n");

/**------------------------------------------------------------------------------------------------------------------------------------------------------------------------------**/

//now retrieve the file by first getting user input for file name and check that the file exists

FILE_CHECK:

printf ("\nEnter the name of file to access >> " );
scanf ("%s", outFileName);
printf ("\nThe name of the file is >> %s\n\n", outFileName);

//now open the file

ptrOut = fopen (outFileName, "r");
if (ptrOut == NULL)
{
    printf ("Sorry, the file does not exist. Re-enter another file-name.\n\n");
    goto FILE_CHECK;
}

//read lines first - total number of lines == total number of rows

for (lines = getc (ptrOut); lines != EOF; lines = getc (ptrOut))
{
    if (lines == '\n')
    {
        ctrLines ++ ;
    }
}

r = ctrLines - 1;

matrixOut = (double **) malloc (r * sizeof (double *));
if (matrixOut == NULL)
{
    printf ("\nSorry, not enough memory!\n\n");
    exit (0);
}

free (matrixOut);

printf ("\nRows >> %d\n\n", r);

/*******************************************************************************************************************************************/

//open the file again to count columns

ptrOut = fopen (outFileName, "r");

for (spaces = getc (ptrOut); spaces != EOF; spaces = getc (ptrOut))
{
    if (spaces == ' ' || spaces == '\t' || spaces == '\b')
    {
        ctrSpaces ++ ;
    }
}

c_temp = ctrSpaces;

c = c_temp / r;

printf ("\nCols >> %d\n\n", c);

for (i = 0; i < r; i ++)
{
    matrixOut [i] = (double *) malloc (c * sizeof (double));
    if (matrixOut [i] == NULL)
    {
        printf ("\nSorry, not enough memory!\n\n");
        exit (0);
    }
}

for (i = 0; i < r; i ++ )
{
    free (matrixOut [i]);
}
fclose (ptrOut);

//reopen the file again to read the matrix elements line by line

ptrOut = fopen (outFileName, "r");

matrixOut = (double **) malloc (r * sizeof (double *));

for (i = 0; i < r; i ++)
{
    matrixOut [i] = (double *) malloc (c * sizeof (double));
}

//print out the matrix here

printf ("\nThe matrix in the file %s of size %d x %d.\n\n", outFileName, r, c);

for (i = 0; i < r; i ++)
{
    for (j = 0; j < c; j++)
    {
        fscanf (ptrOut, "%lf", &matrixVals);
        matrixOut [i] [j] = matrixVals;
        printf ("%.3lf\t", matrixOut [i] [j]);
    }
    printf ("\n");
}
printf ("\n");

printMajorDiagonal (matrixOut, r, c);
printMinorDiagonal (matrixOut, r, c);

for (i = 0; i < r; i ++)
{
    free (matrixOut [i]);
}
free (matrixOut);

fclose (ptrOut);

return (0);
}

//function definitions

void printMajorDiagonal (double ** m, int r, int c)
{
//prints out the major diagonal
int i, j;
if (r == c)
{
    printf ("\nMajor Diagonal >> \n\n");
    for (i = 0; i < r; i ++)
    {
        printf ("%.3lf\t", m [i] [i]);
    }
    printf ("\n");
}
else if (r != c)
{
    printf ("\nThe major diagonal cannot be printed since the given matrix is not a square matrix.\n\n");
}
}

void printMinorDiagonal (double ** m, int r, int c)
{
//prints out the opposite "minor" diagonal
int i, j;
if (r == c)
{
    printf ("\nMinor Diagonal >> \n\n");
    for (i = 0; i < r; i ++)
    {
        printf ("%.3lf\t", m [r - i - 1] [i]);
    }
    printf ("\n");
}
else if (r != c)
{
    printf ("\nThe major diagonal cannot be printed since the given matrix is not a square matrix.\n\n");
}
}

再次感谢所有参与帮助我的人。我的错误是在第一次迭代行计数后没有重新启动文件。

非常感谢StackOverFlow!