Advertisement
zuevv

Hey, Nikita

Nov 23rd, 2018
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #pragma warning(disable : 4996) //for VS to permit fopen
  4. /*Prints all the strings starting from "hello" from file which name is typed in by user*/
  5.    
  6. int  getfilename(char *filename, const int maxlen);
  7. void printstrings(char *filename, char *compareto, const int maxlen);
  8. int main(void) {
  9.     const int maxlen = 100;
  10.     char * filename = (char *)calloc(maxlen + 1, sizeof(char));
  11.     char compareto[] = "hello";
  12.     int flag = getfilename(filename, maxlen);
  13.     if (flag == -1) {
  14.         printf("error: filename too long\n");
  15.         return -1;
  16.     }
  17.     printf("Opening file: %s\n", filename);
  18.     printstrings(filename, compareto, maxlen);
  19.     free(filename);
  20.     return 0;
  21. }
  22.  
  23. int  getfilename(char *filename, const int maxlen) {
  24.     int buf;
  25.     int i = 0;
  26.     printf("enter full path to file\n");
  27.     while ((buf = getc(stdin)) != NULL && buf != '\n' && buf != ' ' && i <= maxlen)
  28.         filename[i++] = buf;
  29.     if (i == maxlen)
  30.         return -1;
  31.     return 0;
  32. }
  33.  
  34. void printstrings(char *filename, char *compareto, const int maxlen) {
  35.     FILE * fp = fopen(filename, "r"); //c://input.txt
  36.     int *buf  = (char *)calloc(maxlen, sizeof(char));
  37.     int i = 0;
  38.     if (fp == NULL) {
  39.         printf("error opening file\n");
  40.         exit(-1);
  41.     }
  42.     while (buf[0] != '\n' && buf[0] != EOF) {
  43.         int flag = 1;
  44.         for (i = 0; i < maxlen && (buf[i] = getc(fp)) != '\n'; i++) {
  45.             if (feof(fp)) {
  46.                 printf("error reading file\n");
  47.                 exit(-1);
  48.             }
  49.             buf[i] ;
  50.         }
  51.         i = 0;
  52.         while (compareto[i] != 0) {
  53.             if (compareto[i] != buf[i]) { //if first substring of buf isn't "hello"
  54.                 flag = 0;
  55.                 break;
  56.             }
  57.             i++;
  58.         }
  59.         if (flag == 1) {
  60.             i = 0;
  61.             while (buf[i] != 0) {
  62.                 putc(buf[i], stdout);
  63.                 buf[i] = 0;
  64.                 i++;
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement