CSM210: Systems Programming in C. Practical Session 1

Solution to strncpy amended to read input from a file



/* prog is called with a.out n [filename] */

/* strmcpy(s, t, n) copy n chars from s to t. */
#include 
#include  /* because this library is included, we have to change the
                       name of our function */

int strmcpy(FILE *,  char *, int n);
/* takes a pointer to FILE, pointer to char, and int */

main(int argc, char *argv[]) {

char copy[10];
int copy_from = 0;// will be the number of chars to copy from source to destination
FILE *fp;
int c;

 if (argc < 2 || argc > 3)
 { printf("Errors in input\n");
 return 0;
 }
 
copy_from=atoi(*(argv+1)); /* convert 2nd param to integer */

// if third arg is present then it's a file name, otherwise take input from stdin

if (argc == 3) {
 if ((fp = fopen(*(argv+2), "r")) == NULL) {
    printf("Error opening file...\n"); 
    return 0;
 } 
} else /* argc is 2 */{
	fp = stdin;
}

// we'll now pass the pointer to standard input or the file, as appropriate

strmcpy(fp, copy, copy_from); 
printf("copy is %s\n", copy);
fclose(fp); // closes the file
}

int strmcpy(FILE *fp, char *copy, int n) {

int k = 0;

 *(copy + n ) = '\0';
 while (n > k) {
  *(copy + k++) = getc(fp);
  // read the next char and store it in the appropriate location in the destination
  // array
 }
 return 1;
}