如何将文件(在C中)加载到全局定义的字符数组中?

时间:2013-11-15 23:16:42

标签: c arrays io

我真的不知道从哪里开始。 I / O并不是我流利的东西。我想声明一个包含文本文件信息的全局字符数组。这个数组的大小必须由inut文件决定。到目前为止,这是我唯一的想法:

    #include<stdio.h>
    int N;
    char c_array[N];
    int main(){
        f = fopen("file.txt","r");
        File *infile;
        c_array[N] = fscanf(f) //Yeah I dont get how fscanf works either
        .........;
    }

大小将由文件大小决定(假设它不是一个荒谬的长度)。该文件(名为file.txt)将包含以下内容:

    A 5 4
    4 C 3
    5 4 4

所以在这种情况下我想要c_array [N] = {A,5,4,4,c,3,5,4,4},其中N = 9。

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

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

char *array;

int main()
{
    FILE* file;
    int sz,i=0;
    char c;
    file=fopen("file.txt","r");

    //get the file size in bytes
    fseek(file,0,SEEK_END);
    sz=ftell(file);
    //allocate the array based on the file size;
    array=(char*)malloc(sz);
    rewind(file);//rewind the file and start reading from the beginning

    while(c!=EOF)
    {
        c=getc(file);
        if(isalnum(c)) //if the character is number or letter save it in the array
        {
                array[i]=c;
                i++;
        }
    }
    fclose(file);
    for(int j=0; j<i; j++)
    {
        printf("%c",array[j]);
    }
    free(array);
    return 0;
}