开发者

reading a file and saving in an array

I want a simple C program, which will read a file and saves the content of e开发者_StackOverflowach line to an array element. The file contains all the integer value. Only one integer value is present per line. In this way each of the integer value is to stored in an array.


Here is an example which does what you ask, with error checking, and dynamically resizing your array as more data is read in.

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

int main(int argc, char ** argv)
{
    char buf[512];
    FILE * f;
    int * array = 0;
    size_t array_len = 0, count = 0;

    if (argc != 2) {
        fprintf(stderr, "Please provide a filename to read\n");
        exit(1);
    }

    f = fopen(argv[1], "r");

    if (f == NULL) {
        perror("fopen");
        exit(1);
    }

    while (fgets(&buf[0], 512, f) != 0) {
        if (count == array_len) {
            array_len *= 2;
            if (array_len == 0) {
                array_len = 32;
            }
            array = realloc(array, array_len * sizeof(int));
            if (array == NULL) {
                perror("realloc");
                exit(1);
            }
        }
        array[count++] = strtol(buf, 0, 10);
    }

    return 0;
}


There are many web resources to help you in this regard. a fast google search pointed me to this example

which, beside the non dynamic nature of the example, does what you want with scanf.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜