1

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;
     }
1
  • Your "approach" looks like a stub code. Have you tried anything else so far? Commented Oct 15, 2014 at 9:33

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.