0

シソーラス ファイルを読み取るシソーラス プログラムを作成しようとしました。ただバグがあるようで、getReplacement()のwhileループに絞り込み、前後の印刷操作を確認しました。うまくいかない理由を誰かが見つけてくれて本当に感謝しています。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <iostream>


char* getReplacement(char* original, FILE* file);

int main(int argc, char* argv[])
{

    using namespace std;

    FILE* thes = fopen(argv[1], "r");
    FILE* text = fopen(argv[2], "r+");
    FILE* nText = fopen("temp.txt", "w");
    if(thes == NULL || text == NULL || nText == NULL)
        return 1;
    char word[20] = {};
    char c;
    int bytesW=0;
    while((c = fgetc(text)) != EOF)
    {
        fputc(c, nText);
        bytesW++;
        if(isalpha(c))
        {
            int len = strlen(word);
            word[len] = c;
            word[len + 1] = '\0';
        }

        else
        {
            if(word == "")
                continue;
            cout << 7<<endl;
            char* replacement = getReplacement(word, thes);
            if(replacement == NULL)
                continue;
            fseek(nText,bytesW-1-strlen(word),SEEK_SET);
            for(int i=0;i<strlen(replacement);i++)
                fputc(replacement[i],nText);
            int diff = strlen(word) - strlen(replacement);
            while(diff-- >0)
                fputc(' ', nText);
            bytesW = bytesW-1-strlen(word)+strlen(replacement);
            fseek(nText, bytesW, SEEK_SET);
        }

    }
    fclose(thes);
    fclose(text);
    fclose(nText);


    return 0;
}

char* getReplacement(char* const original, FILE* file)
{
    using namespace std;
    char* line="";
    const short len = strlen(original);
    int numOfOptions=1;
    int toSkip=0; // number of commas to skip over
    outer: while(fgets(line,1000,file) != NULL)
    {
        for(int i=0;i<len;i++)
            if(line[i] != original[i])
            {
                goto outer;
            }
        if(line[len] != ':') 
            goto outer;
        for(int i=0;i<len;i++)
            line++;
        for(int i=0;i<strlen(line);i++)
            if(line[i] == ',')
                numOfOptions++;
        toSkip = rand()%numOfOptions;
        while(toSkip >0)
        {
            if(line[0] == ',')
                toSkip--;
            line++;
        }
        return line;
    }
    return NULL;

}
4

1 に答える 1