[C language] I'd like to save a string of text files in an array, but I'm curious about the method

Asked 2 years ago, Updated 2 years ago, 120 views

I want to save five strings in a text file in a char pointer array.

Current code.

This is the output screen.

c string text-file

2022-09-20 21:56

1 Answers

Please refer to the code below.

#define _CRT_SECURE_NO_WARNINGS

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

#define MAX 100

int main()
{
    char* n[5];
    char* name;

    FILE* fp = NULL;
    int cnt = 0;

    fp = fopen("Word.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "File Open Error!\n");
        exit(1);
    }

    for (int i = 0; i < 5; i++)
    {
        name = (char*)malloc(sizeof(char) * MAX);
        fgets(name, MAX, fp);
        n[i] = name;
        printf("%s", name);
    }

    printf("\n\n");

    for (int i = 0; i < 5; i++)
        printf("%s", n[i]);

    for (int i = 0; i < 5; i++)
        free(n[i]);

    fclose(fp);

    return 0;
}

Run Results


2022-09-20 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.