0

мне надо пройтись по текстовому файлу, где строки разделены пробелом, и раскидать их в массив. Функция getKeyWord должна сама выделить память и присвоить указателю новый адрес памяти где хранится строка. Она возвращает 1, если прочитала последнее слово в файле, иначе 0.

Компилятор: GNU GCC 9.2.0.

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

char getKeyWord(FILE *f, char **str);
int main(int argc,char *args[])
{
        if (argc!=3)
        {
            printf("error");
            return 0;
        }
        FILE *orig_file;
        if ( !(orig_file = fopen(args[1], "r")) )
        {
            printf("1st path is invalid ");
            return 0;
        }

    size_t count_str = 0, size_buf = 10, step =10;
    char **strings = malloc(sizeof(char*)*size_buf);

    while(1)
    {

        if(getKeyWord(orig_file, strings+count_str))
        {
            printf("%i %s\nEND",count_str, strings[count_str]);
            break;
        }
        printf("%i %s\n\n",count_str+1, strings[count_str]);


        if (++count_str >= size_buf)
        {
            size_buf += step;
            strings = realloc(strings, size_buf);
        }
    }
    return 0;
}
char getKeyWord(FILE* f, char **str)
{
    int c;
    size_t  count_chars = 0, step =10,size_buf = step;
    *str = (char*)malloc(sizeof(char)*size_buf);


    while(1)
    {

        c=fgetc(f);

        putchar(c);
        if (c==' ')
        {
            *(*str+count_chars) = 0;
            putchar('\n');
            return 0;
        }

        if (c==EOF)
        {
            *(*str+count_chars) = 0;
            putchar('\n');
            return 1;
        }
        *(*str+count_chars) = c;
        if (++count_chars >= size_buf)
        {
            size_buf += step;
            *str = realloc(*str,size_buf);
            
        }
    }

    return 0;
}

пример такого файла:

strings string name category text xml version dialog gfx offset size halign valign font button image center left right std hover down color credits speed format align indent space pause time file sfx frame progressbar direction vertical horizontal back front range min max steps caption hover_down disabled top resizedialog animation bottom mid all_objects object type loop oneshot chili right closeddoorback position ms inv closeddoorleft closeddoorright dog region neighbor doorback doorleft doorright woody gfxdata icon actor hotspot start noise action actoranim actornextanim objanim objnextanim auto ms0 ms1 ms2 ms3 volume triggers behavior triggers always once house room level angrytime layer room path1 path2 floor door wall true false costs doorin doorout tricks trick quota1 quota2 quota3 quota4 combination remove ingredient splasher splasher splasher statusbar hide with description wrong nearobj trigger inventar singleuse stdaction open look hideout locale charset install fonts bold slanted leveldata set state playable reachable minquota nextset locked shortcuts key code shortcut function

3
  • Результаты большинства вызовов в C надо проверять, особенно malloc и realloc
    – dIm0n
    24 июл 2020 в 14:42
  • sizeof(char*) забыли?
    – Ainar-G
    24 июл 2020 в 14:51
  • @dIm0n Я сейчас вставил проверку первого malloc'а в функции, но в нем проблемы нет. Проблема в realloc, на котором процесс виснет. Я также пытался написать свой велосипед, но он также виснет когда я пытаюсь выделить память. Причем я в диспетчере смотрел процесс даже 1 мб памяти не занял. 24 июл 2020 в 14:52

1 ответ 1

0

Спасибо @Ainar-G, я тут забыл, когда заново выделял память массива, умножить размер массива на размер указателя.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.