简体   繁体   English

如何读取文件的第一个数字?

[英]How can I read the first number of a file?

I am trying to read numbers from a file and put those numbers into an array.我正在尝试从文件中读取数字并将这些数字放入数组中。 And now the file looks like this:现在文件看起来像这样:

100 100

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 10 11 12 13 14 15 16 17 18 19

20 21 22 23 24 25 26 27 28 29 20 21 22 23 24 25 26 27 28 29

Obviously the first number is the size of the array.显然第一个数字是数组的大小。 While I try to test the read, I got 8. And here's my code:当我尝试测试读取时,我得到了 8。这是我的代码:

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

int main()
{
    FILE * filePtr;
    int firstNum;
    filePtr = fopen("array,dat", "r");
    if(filePtr!=NULL)
    {
    fscanf(filePtr, "%d", &firstNum);
    fclose(filePtr);
    }
    printf("size: %d", firstNum);


    return 0;
}

and this is the result I got:这是我得到的结果:

size: 8
Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

So how can I get the correct number that I want and why does it show 8?那么我怎样才能得到我想要的正确数字,为什么它显示 8?

Because of a typo array,dat -> array.dat , your program fails to open the file.由于输入错误array,dat -> array.dat ,您的程序无法打开文件。 So it will then merely print the contents of the uninitialized variable firstNum , which may contain any garbage value.所以它只会打印未初始化的变量firstNum的内容,其中可能包含任何垃圾值。

It would be better if you wrote your error handling like for example:如果您编写错误处理方式会更好,例如:

if(filePtr==NULL)
{
  printf("Could not open file %s", fileName);
  return 0; // no point in continuing execution after this
}

Try this one试试这个

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

int main()
{

FILE *myFile;
myFile = fopen("array.dat", "r");

//read file into array
int numberArray[100];
int i;

if (myFile == NULL)
{
    printf("Error Reading File\n");
    exit (0);
}else
{
for (i = 0; i < (sizeof( numberArray ) / sizeof( numberArray[0] )); i++)
{
    fscanf(myFile, "%d,", &numberArray[i] );

}

for (i = 0; i <  (sizeof( numberArray ) / sizeof( numberArray[0] )); i++)
{
       printf("Number is: %d\n\n", numberArray[i]);
}
}
fclose(myFile);

return 0;
}

There are many ways to approach this task.有很多方法可以完成这项任务。 The key is making it work regardless of small variations in input format.关键是不管输入格式的微小变化都让它工作。 That is where strtol excels.这就是strtol优势所在。 It also provides much better error analysis on a conversion failure than most.它还提供了比大多数转换失败更好的错误分析。

The example below simply reads your data into an array by reading a line-at-a-time and parsing that line into values with strtol .下面的示例只是通过一次读取一行并使用strtol将该行解析为值来将数据读入数组。 Take a look and give it a try.看一看并尝试一下。 Note the functions below dealing with allocating memory are just to keep the body of the code clean so you can hopefully follow the logic easier without all the allocation validation checks filling up main() .请注意,下面处理分配内存的函数只是为了保持代码主体干净,因此您希望可以更轻松地遵循逻辑,而无需将所有分配验证检查都填满main() Good luck:祝你好运:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>

#define ROWS 3
#define COLS 3
#define MAXC 256

long xstrtol (char *p, char **ep, int base);
void *xcalloc (size_t n, size_t s);
void *xrealloc_sp (void *p, size_t sz, size_t *n);
void *xrealloc_dp (void **p, size_t *n);

int main (void) {

    char line[MAXC] = {0};              /* line buffer for fgets    */
    char *p, *ep;                       /* pointers for strtol      */
    int **array = NULL;                 /* array of values          */
    size_t row = 0, col = 0, nrows = 0; /* indexes, number of rows  */
    size_t rmax = ROWS, cmax = COLS;    /* row/col allocation size  */

    /* allocate ROWS number of pointers to array of int */
    array = xcalloc (ROWS, sizeof *array);

    /* read each line in file */
    while (fgets(line, MAXC, stdin))
    {
        p = ep = line;  /* initize pointer/end pointer      */
        col = 1;        /* start col at 1, store ncols in 0 */
        cmax = COLS;    /* reset cmax for each row          */

        /* allocate COLS number of int for each row */
        array[row] = xcalloc (COLS, sizeof **array);

        /* convert each string of digits to number */
        while (errno == 0)
        {
            array[row][col++] = (int)xstrtol (p, &ep, 10);

            if (col == cmax) /* if cmax reached, realloc array[row] */
                array[row] = xrealloc_sp (array[row], sizeof *array[row], &cmax);

            /* skip delimiters/move pointer to next digit */
            while (*ep && *ep != '-' && (*ep < '0' || *ep > '9')) ep++;
            if (*ep)
                p = ep;
            else  /* break if end of string */
                break;
        }
        array[row++][0] = col; /* store ncols in array[row][0] */

        /* realloc rows if needed */
        if (row == rmax) array = xrealloc_dp ((void **)array, &rmax);
    }
    nrows = row;  /* set nrows to final number of rows */

    printf ("\n the simulated 2D array elements are:\n\n");
    for (row = 0; row < nrows; row++) {
        for (col = 1; col < (size_t)array[row][0]; col++)
            printf ("  %4d", array[row][col]);
        putchar ('\n');
    }
    putchar ('\n');

    /* free all allocated memory */
    for (row = 0; row < nrows; row++)
        free (array[row]);
    free (array);

    return 0;
}

/** a simple strtol implementation with error checking.
 *  any failed conversion will cause program exit. Adjust
 *  response to failed conversion as required.
 */
long xstrtol (char *p, char **ep, int base)
{
    errno = 0;

    long tmp = strtol (p, ep, base);

    /* Check for various possible errors */
    if ((errno == ERANGE && (tmp == LONG_MIN || tmp == LONG_MAX)) ||
        (errno != 0 && tmp == 0)) {
        perror ("strtol");
        exit (EXIT_FAILURE);
    }

    if (*ep == p) {
        fprintf (stderr, "No digits were found\n");
        exit (EXIT_FAILURE);
    }

    return tmp;
}

/** xcalloc allocates memory using calloc and validates the return.
 *  xcalloc allocates memory and reports an error if the value is
 *  null, returning a memory address only if the value is nonzero
 *  freeing the caller of validating within the body of code.
 */
void *xcalloc (size_t n, size_t s)
{
    register void *memptr = calloc (n, s);
    if (memptr == 0)
    {
        fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
        exit (EXIT_FAILURE);
    }

    return memptr;
}

/** reallocate array of type size 'sz', to 2 * 'n'.
 *  accepts any pointer p, with current allocation 'n',
 *  with the type size 'sz' and reallocates memory to
 *  2 * 'n', updating the value of 'n' and returning a
 *  pointer to the newly allocated block of memory on
 *  success, exits otherwise. all new memory is
 *  initialized to '0' with memset.
 */
void *xrealloc_sp (void *p, size_t sz, size_t *n)
{
    void *tmp = realloc (p, 2 * *n * sz);
#ifdef DEBUG
    printf ("\n  reallocating '%zu' to '%zu', size '%zu'\n", *n, *n * 2, sz);
#endif
    if (!tmp) {
        fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
        exit (EXIT_FAILURE);
    }
    p = tmp;
    memset (p + *n * sz, 0, *n * sz); /* zero new memory */
    *n *= 2;

    return p;
}

/** reallocate memory for array of pointers to 2 * 'n'.
 *  accepts any pointer 'p', with current allocation of,
 *  'n' pointers and reallocates to 2 * 'n' pointers
 *  intializing the new pointers to NULL and returning
 *  a pointer to the newly allocated block of memory on
 *  success, exits otherwise.
 */
void *xrealloc_dp (void **p, size_t *n)
{
    void *tmp = realloc (p, 2 * *n * sizeof tmp);
#ifdef DEBUG
    printf ("\n  reallocating %zu to %zu\n", *n, *n * 2);
#endif
    if (!tmp) {
        fprintf (stderr, "%s() error: virtual memory exhausted.\n", __func__);
        exit (EXIT_FAILURE);
    }
    p = tmp;
    memset (p + *n, 0, *n * sizeof tmp); /* set new pointers NULL */
    *n *= 2;

    return p;
}

Compile编译

gcc -Wall -Wextra -Ofast -o bin/array_ukn_size array_ukn_size.c

Input输入

$ cat ../dat/10by10.txt
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

Output输出

$ ./bin/array_ukn_size <../dat/10by10.txt

 the simulated 2D array elements are:

     0     1     2     3     4     5     6     7     8     9
    10    11    12    13    14    15    16    17    18    19
    20    21    22    23    24    25    26    27    28    29
    30    31    32    33    34    35    36    37    38    39
    40    41    42    43    44    45    46    47    48    49
    50    51    52    53    54    55    56    57    58    59
    60    61    62    63    64    65    66    67    68    69
    70    71    72    73    74    75    76    77    78    79
    80    81    82    83    84    85    86    87    88    89
    90    91    92    93    94    95    96    97    98    99

For example your input file name is input.txt .Now save this file with your source(.c) file same folder.例如,您的输入文件名是input.txt 。现在将此文件与您的源(.c)文件保存在同一文件夹中。 now you can read input file by this way现在您可以通过这种方式读取输入文件

freopen("input.txt","r",stdin); 

Here full code这里完整代码

#include <stdio.h>

int main()
{
    int firstNum,otherNum;
    freopen("input.txt","r",stdin);
    scanf("%d",&firstNum);// this read first number 100
    while(scanf("%d",&otherNum)==1)// this loop continue until end of file
    {
         // hear you get other numbers
         printf("%d",otherNum) ; // this line print 0 1 2 3 to 99
    }
    return 0;
}

Note :Use Code::Blocks IDE注意:使用Code::Blocks IDE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM