Siva Makani
Siva Makani

Reputation: 216

C program to extract different substrings from array of strings

I want to extract different substrings from a file with array of strings. My file resembles this.

abcdxxx
efghijkyyy
lmzzz
ncdslanclsppp
kdfmsqqq
cbskdnsrrr 

From the above file I want to extract xxx, yyy, zzz, ppp, qqq, rrr (basically last 3 characters) and store into an array. I refered this link How to extract a substring from a string in C? but not felt feasible because the content in my file is dynamic and might change for next execution. Can someone give a brief on this? Here is my approach

     FILE* fp1 = fopen("test.txt","r");
     if(fp1 == NULL)
     {
        printf("Failed to open file\n");
        return 1;
     }
     char array[100];
     while(fscanf(fp1,"%[^\n]",array)!=NULL);

     for(i=1;i<=6;i++)
     {
        array[i] += 4;
     }

Upvotes: 1

Views: 448

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

the content in my file is dynamic and might change for next execution

Then you need realloc or a linked list:

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

int main(void)
{
    FILE *f;
    char **arr = NULL;
    char s[100];
    size_t i, n = 0;

    f = fopen("text.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(s, sizeof s, f) != NULL) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        arr[n] = calloc(4, 1);
        memcpy(arr[n++], s + strlen(s) - 4, 3);
    }
    fclose(f);
    for (i = 0; i < n; i++) {
        printf("%s\n", arr[i]);
        free(arr[i]);
    }
    free(arr);
    return 0;
}

Output:

xxx
yyy
zzz
ppp
qqq
rrr

If you always want the last 3 characters you can simplify:

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

int main(void)
{
    FILE *f;
    char (*arr)[4] = NULL;
    char s[100];
    size_t i, n = 0;

    f = fopen("text.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(s, sizeof s, f) != NULL) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        memcpy(arr[n], s + strlen(s) - 4, 3);
        arr[n++][3] = '\0';
    }
    fclose(f);
    for (i = 0; i < n; i++) {
        printf("%s\n", arr[i]);
    }
    free(arr);
    return 0;
}

Upvotes: 1

Related Questions