Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * F14. (3 puncte) Scrieti un program care numara aparitiile unui string
- * intr-un fisier dat. Stringul si specificatorul fisierului sunt dati ca
- * argumente in linia de comanda.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int stringLen(FILE *f)
- {
- size_t pos = ftell(f); // Current position
- fseek(f, 0, SEEK_END); // Go to end
- size_t length = ftell(f); // read the position which is the size
- fseek(f, pos, SEEK_SET); // restore original position
- return length;
- }
- int main(int argc, char **argv)
- {
- FILE *input;
- char *string;
- int tempWord;
- int wordLen;
- int appearance;
- int fs;
- int chars;
- int stringFileLen;
- //We check if we do not have 3 arguments
- if(argc != 3)
- {
- fprintf(stderr, "Three arguments required!\nUse: %s word file\n", argv[0]);
- return 1;
- }
- //If we have 3 arguments, it's oK
- tempWord = strlen(argv[1]);
- wordLen = strlen(argv[1]);
- //if word is null, then stop
- if(!wordLen)
- {
- fprintf(stderr, "The second argument is NULL.\n A word with a minimum of length of 1 is required.\n");
- return 1;
- }
- //if word is not null, it's ok
- input = fopen(argv[2], "r");
- //We check if the file works
- if(input == NULL)
- {
- perror(argv[2]);
- return 1;
- }
- stringFileLen = stringLen(input);
- printf("MARIME: %d\n", stringFileLen);
- //We allocate memory to string, which is equal to the length of argv[1]
- string = (malloc((sizeof(char)*(wordLen + 1))));
- if(string == NULL)
- {
- perror("malloc");
- fclose(input);
- return 1;
- }
- appearance = 0;
- chars = 0;
- while(tempWord == wordLen)
- {
- if((chars + wordLen) <= stringFileLen)
- {
- //We read every wordLen string of input and place it on the tempWord
- tempWord = fread(string, sizeof(char), wordLen, input);
- if(ferror(input))
- {
- perror(argv[2]);
- fclose(input);
- return 1;
- }
- string[wordLen] = '\0';
- if(strcmp(string, argv[1]) == 0)
- appearance++;
- fs = fseek(input, 1 - wordLen, SEEK_CUR);
- chars++;
- if(fs == -1)
- {
- fprintf(stderr, "Searching Error...\n");
- fclose(input);
- return 1;
- }
- }
- else
- break;
- }
- if(appearance < 1) fprintf(stdout, "The %s word does not belong to the file %s.\n", argv[1], argv[2]);
- else
- {
- if(appearance == 1) fprintf(stdout, "The %s word appears only once in the file %s.\n", argv[1], argv[2]);
- else fprintf(stdout, "The %s word appears %d times in the file %s.\n", argv[1], appearance, argv[2]);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement