Проблема с открытием и редактированием в файле - PullRequest
0 голосов
/ 06 января 2020

Итак, у меня есть это задание (первый класс программирования, который я беру), в котором нам нужно добавить что-то в список покупок, позволить пользователю сохранить список в виде файла .txt, закрыть программу, загрузить любой файл (по входу пользователя, который файл, чтобы открыть), а затем возможность редактировать в загруженном файле. На данный момент это две функции, которые я получил для сохранения файла и загрузки файла:

Сохранить:

void saveList(struct ShoppingList* list)    //  Function that saves the list to a .txt file
{
    FILE* fileHandler;                      //  When the file is called we call "filehandler" (like a temp name)
    char input[20];                         
    input[0] = '\0';                        //  if the input array is empty, charachter 0 is the last one

    printf("Enter the name of the .txt file (without the '.txt') where you want to save your shoppinglist\n(If it doesn't exist already, the program will create it for you): ");
    scanf_s("%s", input, 20);               //  Takes input from the user, this will be the file that is created and the list saved to, will be stored in "input"

    fileHandler = fopen(input, "w");        //  filehandler will open and write to a file, with the name stored in "input"
    if (fileHandler == NULL)                //  If filehandler is NULL
    {
        printf("Error!\n");                 //  Probbably because it could not create the file.
        return;
    }
    for (int i = 0; i < list->length; i++)  //  When filehandler is NOT NULL (more or less)
    {
        fprintf(fileHandler, "%s %0.2f %s\n", list->itemList[i].productName, list->itemList[i].amount, list->itemList[i].unit);
    }
    fclose(fileHandler);                    //  Close the file when we are done with it (save it).
}

И это текущая нагрузка (вот где у меня проблемы, объясню под кодом):

void loadList(struct ShoppingList* list)    //  Function that can load a saved list from a .txt file
{
    FILE* fileHandler;
    char filename[100], c;

    printf("Enter the name of the file you want to open: ");
    scanf("%s", filename);

    fileHandler = fopen(filename, "r");            // Open file 
    if (fileHandler == NULL)
    {
        printf("File does not exist / The file cannot be opened \n");
        return;
    }

    while (fgets(filename, 100, fileHandler) != NULL)
    {
        printf("%s", filename);
    }

    fclose(fileHandler);                        //fileHandler is done and shuts the file down
    return 0;
}

В настоящее время я могу загрузить файл, который программа распечатывает, но затем, когда я хочу снова отобразить загруженный файл (отображение текущих элементов в список покупок - это то, что пользователь может сделать, может отправить этот код, если кто-то сочтет это необходимым), он возвращает «список пуст». что делать, если список был бы пустым, но я только что загрузил в файл со списком?

В настоящее время мои знания ограничены, и сейчас я просто бьюсь об это. Помощь ценится.

...