从2D数组中的文件存储中读取单词

时间:2014-01-06 16:22:14

标签: c file-io

我正在尝试使用C中的“动态”数组。我想要读取此代码

printer,kekroflmeow,augustus,rofl,mao,kek,burger,lol,zomg,apo,abe,ago,lorem,ipsum,solar,sit,whan,kong,ping,roflstomp,dennis,hotdog,ketchup,viva,north

并将其存储在2D数组中(动态地,我希望能够添加和删除单词)。单词不能超过20个字符。我得到它主要工作,我有两个问题,char ** str是从主文件变量是char * mWords [20],然而,这显然意味着它可以包含20个具有未定义长度的单词,这是相反的我想要的是什么。

您可能还需要getWordsFroMFile(char ** str)函数。

// get words from file; delimiter , stores them in str[word][character]
int getWordsFromFile (char **str) {
    FILE *tFile;

    int file_size;
    char *file_ptr;

    // load the file and check if it exists
    tFile = fopen(FILENAME, "r");
    if (tFile == NULL) {
        printf ("Cannot open file '%s'", FILENAME);
        exit (1);
    }

    // get size of file in bytes (1 byte = 1 char)
    fseek (tFile , 0 , SEEK_END);
    file_size = ftell (tFile);

    // back to start of tFile
    rewind (tFile);

    // allocate memory
    file_ptr = (char*) malloc (file_size);
    if (file_ptr == NULL) {
        printf ("Could not read file '%s'", FILENAME);
        exit (2);
    }

    // file -> buffer
    int size = fread (file_ptr, 1, file_size, tFile);
    file_ptr[size] = '\0';
    fclose(tFile);

    char * pch;
    pch = strtok (file_ptr, ",");

    int tWords = 0;
    while (pch != NULL) {
        if (sizeof(pch) < MAX_WORD_LEN && pch != "") {

            // if word only contains valid characters A-Z and/or a-z
            if (isValidWord(pch)) {
                // good, remove trim word and place it in str[tWords]
                str[tWords++] = trimWord(pch);
            } else {
                printf ("Invalid word in '%s': '%s' contains illegal characters.\n", FILENAME, pch);
            }
        }
        pch = strtok (NULL, ",");
    }

    return tWords;
}

从main.cpp调用它(MAX_WORD_LEN是20)

char *mWords[MAX_WORD_LEN];
int mWordsCount = getWordsFromFile (mWords);

更新了fread()以添加终止\ 0

提前致谢,

EMZ

0 个答案:

没有答案