pts Implement the function repeatstring that has the prototype below The

Pts implement the function repeatstring that has the

This preview shows page 3 - 6 out of 9 pages.

Problem #2 (50 pts) Implement the function repeat_stringthat has the prototype below. The function reads a string and an integer from a file and returns a dynamically-allocated string where the string read has been repeated a number of times that corresponds to the integer value. Notice that after each instance of the original string, an asterisk (*) will be appended to the string. The following driver and associated output illustrates the use of the function you need to write. Driver: int main() { char *p = repeat_string("data.txt"); printf("%s\n", p); free(p); return 0; } data.txt John 3 Output: John*John*John* For this problem: You can assume the file will have correct data (a string, followed by an integer greater than or equal to 1). The function will return NULL if opening the file fails or if memory allocation fails. For this problem the only functions from the string library that you can use are:ochar *strncpy(char *dest, const char *src, size_tn) This function is similar to strcpy, except that at most nbytes of srcare copied. Warning: If there is no null byte among the first nbytes of src, the string placed in destwill not be null-terminated. ochar *strcpy(char *dest, const char *src);osize_t strlen(const char *s); You will lose most of the credit for this question if you use functions from the string library not listed above. Prototypes for input/output functions (in case you need them). oFILE *fopen(const char *path, const char *mode); ochar *fgets(char *s, int size, FILE *stream); oint fputs(const char *s, FILE *stream);
Image of page 3
4 o int fscanf(FILE *stream, const char *format, ...); o int sscanf(const char *str, const char *format, ...); char *repeat_string(const char *filename) One Possible Answer char *repeat_string(const char *filename) { char *answer, *p; int i, original_length, instances; char original[MAX_NAME_LENGTH + 1]; FILE *input; if (!(input = fopen(filename, "r"))) { return NULL; } fscanf(input, "%s %d", original, &instances); original_length = strlen(original); p = answer = malloc((original_length + 1) * instances + 1); if (p == NULL) { return NULL; } for (i = 1; i <= instances; i++) { strcpy(p, original); p += original_length; *p = '*'; p++; } *p = '\0'; /* terminating string with nul character */ return answer; }
Image of page 4
5
Image of page 5
Image of page 6

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture