簡體   English   中英

如何讀取文件的第一個數字?

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

我正在嘗試從文件中讀取數字並將這些數字放入數組中。 現在文件看起來像這樣:

100

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

顯然第一個數字是數組的大小。 當我嘗試測試讀取時,我得到了 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;
}

這是我得到的結果:

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

那么我怎樣才能得到我想要的正確數字,為什么它顯示 8?

由於輸入錯誤array,dat -> array.dat ,您的程序無法打開文件。 所以它只會打印未初始化的變量firstNum的內容,其中可能包含任何垃圾值。

如果您編寫錯誤處理方式會更好,例如:

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

試試這個

#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;
}

有很多方法可以完成這項任務。 關鍵是不管輸入格式的微小變化都讓它工作。 這就是strtol優勢所在。 它還提供了比大多數轉換失敗更好的錯誤分析。

下面的示例只是通過一次讀取一行並使用strtol將該行解析為值來將數據讀入數組。 看一看並嘗試一下。 請注意,下面處理分配內存的函數只是為了保持代碼主體干凈,因此您希望可以更輕松地遵循邏輯,而無需將所有分配驗證檢查都填滿main() 祝你好運:

#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;
}

編譯

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

輸入

$ 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

輸出

$ ./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

例如,您的輸入文件名是input.txt 。現在將此文件與您的源(.c)文件保存在同一文件夾中。 現在您可以通過這種方式讀取輸入文件

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

這里完整代碼

#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;
}

注意:使用Code::Blocks IDE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM