首页 > 解决方案 > 使用 strtok 和数组从文件读取并写入另一个文件

问题描述

我有一个关于使用该strtok函数的 C 语言的项目。我正在使用 while 循环读取文件,并且我正在使用分隔符“”(空格)不断地对句子中的单词进行标记。当我阅读文件时,如果我在文件 A 中遇到我用 if 语句指定的单词,我必须将特定的行写入文件 B(宏处理器的扩展)。问题是,每当我尝试从文件 A 中读取并分别写入文件 BI 中的每一行时,我只会从文件 A 中获取最后一行,我需要检查每一行并逐一写入。

while(fgets(str,100,fp) != NULL){
    fgets(str,100,fp);
    if (str[0] == '@')
    {
        char *array[300];
        char *p = strtok (str," \n");
        while (p != NULL)  //tokenize the words, and save into array
        {
            array[i++] = p;
            p = strtok (NULL, " ");
        }
        if (!strcmp(array[0],"@def"))  // if the very first word encountered in the line is @def, write the words below into the file B
        {
            fprintf(fptr2, "define %s %s\n",array[1],array[2]);
        } //defining a global variable
        else if (!strcmp(array[0],"@mat"))// if the very first word encountered in the line is @mat, write the words below into the file B
        {
            fprintf(fptr2, "int %s[%s][%s]\n",array[1],array[2],array[3]); 
        }//defining a 2 dimensional array with dimensions MxN
    }
}

如果文件 A 包含以下行:

@mat A N M
@def N 100

文件 B 将仅写入此行:

define N 100

但它应该有

int A[N][M]
define N 100

同样,如果文件 A 包含以下行:

@def N 100
@mat A N M

文件 B 将在此处写入这一行:

int A[N][M]

但它应该有

define N 100
int A[N][M]

标签: cfile-iostrtok

解决方案


推荐阅读