Search code examples
cstringfilecopymultiple-columns

How can I copy some strings from file to another using c programming


I have this code:

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

int main()
{

    FILE* ptr = fopen("data.txt","r");
    char filename[100];
    if (ptr==NULL)
    {
        printf("no such file.");
        return 0;
    }
 
    char buf[100];
    while (fscanf(ptr,"%*s %*s %s ",buf)==1)
        printf("%s\n", buf);



printf("Create a file \n");
    scanf("%s", filename);
  
    fptr2 = fopen(filename, "w");
    if (fptr2 == NULL)
    {
        printf("Cannot open file %s \n", filename);
        exit(0);
    }
 


    c = fgetc(fptr1);
    while (c != EOF)
    {
        fputc(c, fptr2);
        c = fgetc(fptr1);
    }
  
    printf("\nContents copied to %s", filename);
  
    fclose(fptr1);
    fclose(fptr2);
    return 0;
}



}

It coppies full content from one file to another. I need to copy only strings that have 5 as the last character (3 column)

For example Data.txt looks like that:

Alex 10B 4
John 10A 3
Kate 10C 5

In file that I will create during execution has to be coppied only Kate 10C 5 string. I've been trying for hours but I don't know how to do this. Can you help me?


Solution

  • In the end of each line there is a newline character, (\n) you can use that to read line by line and copy only the ones that you want:

    FILE* dest = fopen("out.txt", "w+"); // supressed null check for simplicity
    
    char buf[100];
    
    char* char_to_find;
    
    // parse line by line
    while (fscanf(ptr, " %99[^\n]", buf) == 1){
         
        char_to_find = buf;
        
        // reach the end of the line
        while(*char_to_find){
            char_to_find++;
        }
        
        //move one back
        char_to_find--;
        
        // if it's 5 save, if not move on
        if(*char_to_find == '5' && *(char_to_find - 1) == ' '){
                        
            fputs(buf, dest);
        }
    }
    

    Live demo