Why doesn’t my C program save the inputs to file using the FILE function?

I just learned C and I’m trying to save the inputs from the user when the code runs, but then it seems that I cannot store the inputs especially for saving the inputs when I rerun the file again. I would like to be able to store the inputs even if the code is runs again. Your help is greatly appreciated!

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

#define MAX_ITEMS 100

typedef struct
{
    char itemName[50];
    float price;
    int stock;
    char keyword[20];
} InventoryItem;

void addItem(InventoryItem items[], int *count);
void editItem(InventoryItem items[], int count);
void deleteItem(InventoryItem items[], int *count);
void displayItems(const InventoryItem items[], int count);
void searchItems(const InventoryItem items[], int count);
void saveToFile(const InventoryItem items[], int count);
void loadFromFile(InventoryItem items[], int *count);

int main()
{
    InventoryItem items[MAX_ITEMS];
    int count = 0;
    int choice;

    loadFromFile(items, &count);

    while (1)
    {
        printf("Menu:n");
        printf("1. Add Itemn");
        printf("2. Edit Itemn");
        printf("3. Delete Itemn");
        printf("4. Display Itemsn");
        printf("5. Search Itemsn");
        printf("6. Exitn");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            addItem(items, &count);
            break;
        case 2:
            editItem(items, count);
            break;
        case 3:
            deleteItem(items, &count);
            break;
        case 4:
            displayItems(items, count);
            break;
        case 5:
            searchItems(items, count);
            break;
        case 6:
            saveToFile(items, count);
            return 0;
        default:
            printf("Invalid choice!n");
        }
    }

    return 0;
}

void addItem(InventoryItem items[], int *count)
{
    if (*count >= MAX_ITEMS)
    {
        printf("Inventory is full!n");
        return;
    }

    printf("Enter item name: ");
    getchar(); // Clear newline from buffer
    fgets(items[*count].itemName, sizeof(items[*count].itemName), stdin);
    items[*count].itemName[strcspn(items[*count].itemName, "n")] = '';

    printf("Enter price: ");
    scanf("%f", &items[*count].price);

    printf("Enter stock: ");
    scanf("%d", &items[*count].stock);

    printf("Enter keyword: ");
    getchar(); // Clear newline from buffer
    fgets(items[*count].keyword, sizeof(items[*count].keyword), stdin);
    items[*count].keyword[strcspn(items[*count].keyword, "n")] = '';

    (*count)++;
    printf("Item added successfully!n");

    saveToFile(items, *count);
}

void editItem(InventoryItem items[], int count)
{
    if (count == 0)
    {
        printf("No items to edit.n");
        return;
    }

    int index;
    printf("Enter item number to edit (1 to %d): ", count);
    scanf("%d", &index);
    if (index < 1 || index > count)
    {
        printf("Invalid item number.n");
        return;
    }
    index--; // Convert to zero-based index

    printf("Editing item #%dn", index + 1);

    printf("Enter new item name: ");
    getchar(); // Clear newline from buffer
    fgets(items[index].itemName, sizeof(items[index].itemName), stdin);
    items[index].itemName[strcspn(items[index].itemName, "n")] = '';

    printf("Enter new price: ");
    scanf("%f", &items[index].price);

    printf("Enter new stock: ");
    scanf("%d", &items[index].stock);

    printf("Enter new keyword: ");
    getchar(); // Clear newline from buffer
    fgets(items[index].keyword, sizeof(items[index].keyword), stdin);
    items[index].keyword[strcspn(items[index].keyword, "n")] = '';

    printf("Item updated successfully!n");

    saveToFile(items, count);
}

void deleteItem(InventoryItem items[], int *count)
{
    if (*count == 0)
    {
        printf("No items to delete.n");
        return;
    }

    int index;
    printf("Enter item number to delete (1 to %d): ", *count);
    scanf("%d", &index);
    if (index < 1 || index > *count)
    {
        printf("Invalid item number.n");
        return;
    }
    index--; // Convert to zero-based index

    for (int i = index; i < *count - 1; i++)
    {
        items[i] = items[i + 1];
    }

    (*count)--;
    printf("Item deleted successfully!n");

    saveToFile(items, *count);
}

void displayItems(const InventoryItem items[], int count)
{
    if (count == 0)
    {
        printf("No items to display.n");
        return;
    }

    printf("Inventory Items:n");
    for (int i = 0; i < count; i++)
    {
        printf("Item #%dn", i + 1);
        printf("Name: %sn", items[i].itemName);
        printf("Price: %.2fn", items[i].price);
        printf("Stock: %dn", items[i].stock);
        printf("Keyword: %snn", items[i].keyword);
    }
}

void searchItems(const InventoryItem items[], int count)
{
    if (count == 0)
    {
        printf("No items to search.n");
        return;
    }

    char keyword[20];
    printf("Enter keyword to search: ");
    getchar(); // Clear newline from buffer
    fgets(keyword, sizeof(keyword), stdin);
    keyword[strcspn(keyword, "n")] = '';

    printf("Search Results:n");
    int found = 0;
    for (int i = 0; i < count; i++)
    {
        if (strstr(items[i].keyword, keyword) != NULL)
        {
            printf("Item #%dn", i + 1);
            printf("Name: %sn", items[i].itemName);
            printf("Price: %.2fn", items[i].price);
            printf("Stock: %dn", items[i].stock);
            printf("Keyword: %snn", items[i].keyword);
            found = 1;
        }
    }

    if (!found)
    {
        printf("No items found with the keyword "%s".n", keyword);
    }
}

void saveToFile(const InventoryItem items[], int count)
{
    FILE *file = fopen("inventory.txt", "w"); 
    if (file == NULL)
    {
        printf("Error opening file for saving.n");
        return;
    }

    for (int i = 0; i < count; i++)
    {
        fprintf(file, "%sn", items[i].itemName);
        fprintf(file, "%.2fn", items[i].price);
        fprintf(file, "%dn", items[i].stock);
        fprintf(file, "%sn", items[i].keyword);
    }

    fclose(file);
    printf("Items saved to file successfully!n");
}


// file opening
void loadFromFile(InventoryItem items[], int *count)
{
    FILE *file = fopen("inventory.txt", "w");
    if (file == NULL)
    {
        printf("No existing inventory file found. Starting fresh.n");
        return;
    }

    while (!feof(file) && *count < MAX_ITEMS)
    {
        if (fgets(items[*count].itemName, sizeof(items[*count].itemName), file) == NULL)
            break;
        items[*count].itemName[strcspn(items[*count].itemName, "n")] = '';

        fscanf(file, "%fn", &items[*count].price);
        fscanf(file, "%dn", &items[*count].stock);

        fgets(items[*count].keyword, sizeof(items[*count].keyword), file);
        items[*count].keyword[strcspn(items[*count].keyword, "n")] = '';

        (*count)++;
    }

    fclose(file);
    printf("Items loaded from file successfully! %d items found.n", *count);
}

I tried changing the file mode to “a” to append the inputs, but still, when I run the code again, no previous file is present, it says.

“No existing inventory file found. Starting afresh.”

And, when I try to save the input to the file, it says
“Error opening file for saving.”

New contributor

congi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật