How to cut part of a string in c?

answerSeeker picture answerSeeker · Dec 3, 2013 · Viewed 76.7k times · Source

I'm trying to figure out how to cut part of a string in C. For example you have this character string "The dog died because a car hit him while it was crossing the road" how would a function go making the sentence "a car hit him while crossing the road" or "a car hit him"

How do you go about this with C's library (or/and) a custom function?

ok I don't have the main code but this is going to be the structure of this experiment

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include "display_usage.c"/*If the user enters wrong arguments it will tell them how it should be */


void cut( const char *file, int option, int first, int last );


int main(int argc, char *argv[] ) {
FILE *fp;
    char ch;
    fp = fopen("test.txt", "r"); // Open file in Read mode

    while (ch!=EOF) {
        ch = fgetc(fp); // Read a Character

        printf("%c", ch);
    }
    fclose(fp); // Close File after Reading
   return 0;
}

void cut( const char *file, int reverse, int first, int last ) {



    return;
}

Answer

woolstar picture woolstar · Dec 3, 2013

strncpy will only copy up to n characters. Optionally you can move a pointer around in the string, and also stick a \0 into the array to terminate it early if you have writable memory.