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

Time:11-21

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?

CodePudding user response:

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, "            
  • Related