파일에서 배열을 읽는 방법에는 여러 가지가 있습니다. 여러분의 도전 과제는 파일에서 두 문자와 정수을 읽은 다음 문자가 숫자를 나타내는 지 여부 또는 값을 대체 할 단일 문자 'x'인지 여부에 따라 요소를 배열에 추가해야한다는 단순한 복잡성을 추가합니다 '99999'
가장 쉬운 방법은 행 지향 입력을 데이터 파일에서 한 번에 한 행씩 읽은 다음 필요에 따라 각 행을 구문 분석하는 것입니다. 모든 라인 입력 요구 사항에 대해 getline
으로 친구를 사귈 것을 권합니다. fgets
또는 scanf
이상의 여러 가지 이점을 제공하며 다른 기능보다 많은 노력을 필요로하지 않습니다.
입력에서 데이터 행을 읽은 후에는 그 행을 단어로 분할해야합니다. strtok
이 선택 도구입니다. 그렇지 않으면 필요에 따라 사용자 지정 파서를 작성할 수 있습니다. 여기서 strtok
이 잘 작동합니다. 행을 단어로 분리 할 때 각 단어를 테스트하여 문자가 숫자인지 문자인지를 판별 할 수 있습니다. 이를 수행 할 수있는 많은 방법이 있습니다. 첫 번째 문자가 'x'
인지 여부를 테스트하는 것이 간단하고 효율적인 방법입니다. 그렇다면 배열 값으로 99999
을 사용하고 그렇지 않으면 atoi (word)
을 사용하여 단어를 정수로 변환하십시오.
다음은 위의 모든 작업을 수행 할 때의 해킹입니다. 읽어보고 궁금한 점이 있으면 알려주십시오.
죄송합니다 원래 대신 '99999'의 '9999'한 - 고정
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1024
int main (int argc, char **argv) {
if (argc < 2) {
fprintf (stderr, "Error: insufficient input. Usage: %s input_file\n", argv[0]);
return 1;
}
char *line = NULL; /* forces getline to allocate space for buf */
ssize_t read = 0; /* number of characters read by getline */
size_t n = 0; /* limit number of chars to 'n', 0 no limit */
int idx = 0; /* simple index counter for array */
int row = 0; /* simple row counter index for array */
int *col = NULL; /* simple column counter for array */
int *array = NULL; /* array to hold integers read from file */
char *delim = " \n"; /* delimeter for strtok to parse line */
FILE *ifp = fopen(argv[1],"r");
if (!ifp)
{
fprintf(stderr, "\nerror: failed to open file: '%s'\n\n", argv[1]);
return 1;
}
array = calloc (MAX_SIZE, sizeof (array)); /* allocate MAX_SIZE elements */
col = calloc (MAX_SIZE, sizeof (col)); /* allocate MAX_SIZE elements */
while ((read = getline (&line, &n, ifp)) != -1) /* read each line in file with getline */
{
char *tmp = NULL; /* pointer to hold strtok results */
tmp = strtok (line, delim); /* first call to strtok using 'line' */
if (*tmp == 'x') /* test if tmp[0] = 'x' */
array [idx++] = 99999; /* if so, assign value of '99999' */
else
array [idx++] = atoi (tmp); /* if not, assign result of atoi (tmp) */
col[row]++; /* increase column count */
while ((tmp = strtok (NULL, delim)) != NULL) /* all remaining strtok calls use NULL */
{
if (*tmp == 'x') /* same tests as above */
array [idx++] = 99999;
else
array [idx++] = atoi (tmp);
col[row]++; /* increase column count */
}
row++; /* increase row count */
}
if (line) free (line); /* free memory allocated by getline */
int it = 0; /* simple index iterator */
while (col[it]) /* simple loop to validate columns */
{
if (it > 0)
if (col[it-1] != col[it])
{
fprintf (stderr, "Error: inconsistent colums of data read\n");
return 0;
}
it++;
}
printf ("\nProperties of array read from file '%s':\n\n", argv[1]);
printf (" elements: %d\n rows : %d\n cols : %d\n", idx, row, col[0]);
printf ("\nArray elements:\n\n");
for (it = 0; it < idx; it++) /* output information stored in array */
{
if ((it+1) % col[0] == 0 && it > 0)
printf (" %5d\n", array[it]);
else
printf (" %5d", array[it]);
}
printf ("\n");
if (array) free (array); /* free memory allocated to arrays */
if (col) free (col);
return 0;
}
입력 파일 :
$ cat dat/graph.txt
0 x x x x x
x 0 x x x x
x x 0 x x x
x x x 0 x x
x x x x 0 x
x x x x x 0
출력 :
$ /bin/rgraph dat/graph.txt
Properties of array read from file 'dat/graph.txt':
elements: 36
rows : 6
cols : 6
Array elements:
0 99999 99999 99999 99999 99999
99999 0 99999 99999 99999 99999
99999 99999 0 99999 99999 99999
99999 99999 99999 0 99999 99999
99999 99999 99999 99999 0 99999
99999 99999 99999 99999 99999 0
을 "#define x 99999"는 여러분이 생각하는 것을하지 않을 것입니다 - 입력을 읽는 동안 런타임에 아무런 영향을 미치지 않습니다. 또한,'if [if] 문 안에'input [size] [size]'를 선언하면'printMatrix (input) '문과 같이 중괄호로 묶인 범위 밖에서 접근 할 수 없다. '진술. –