Advertisement
Bonisek

name, extension, file

May 6th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char *readText()
  6. {
  7.     char *data = malloc(sizeof(char));
  8.     char c;
  9.     int  i = 0;
  10.     fread(&c, 1, 1, stdin);
  11.     while(c != '\n'){
  12.         data = realloc(data, i+2);
  13.         data[i] = c;
  14.         i++;
  15.         fread(&c, 1, 1, stdin);
  16.     }
  17.         data[i] = '\0';
  18.  
  19.     return data;
  20. }
  21.  
  22. int main()
  23. {
  24.     do{
  25.         printf("> Type 'quit' to end testing.\n");
  26.         printf("> Enter the name of file: ");
  27.         char *words = readText();
  28.         if(!strcmp(words, "quit")){
  29.             free(words);
  30.             return 0;
  31.         }
  32.         int extLen = 0;
  33.         int nameLen;
  34.         int total;
  35.  
  36.         if(words[0] == '.'){
  37.             nameLen = strlen(words);
  38.             char orig[nameLen];
  39.             strcpy(orig, words);
  40.             words++;
  41.             char *ext = strrchr(words, '.');
  42.             if(ext){
  43.                 extLen = strlen(ext);
  44.                 if(extLen == 1){
  45.                     printf("Extension: '(none)'\n");
  46.                 }else{
  47.                     printf("Extension: '%s'\n", ext+1);
  48.                 }
  49.             }else{
  50.                 printf("Extension: '(none)'\n");
  51.             }
  52.             total = nameLen-extLen;
  53.             char name[total];
  54.             strncpy(name, orig, total);
  55.             name[total] = '\0';
  56.             printf("name: '%s'\n", name);
  57.  
  58.         }else{
  59.             nameLen = strlen(words);
  60.             char *ext = strrchr(words, '.');
  61.             if(ext){
  62.                 extLen = strlen(ext);
  63.                 if(extLen == 1){
  64.                     printf("Extension: '(none)'\n");
  65.                 }else{
  66.                     printf("Extension: '%s'\n", ext+1);
  67.                 }
  68.             }else{
  69.                 printf("Extension: '(none)'\n");
  70.             }
  71.             total = nameLen-extLen;
  72.             char name[total];
  73.             strncpy(name, words, total);
  74.             name[total] = '\0';
  75.             if(name[0] == '\0'){
  76.                 printf("name: '(none)'\n");
  77.             }else{
  78.                 printf("name: '%s'\n", name);
  79.             }
  80.         }
  81.  
  82.         free(words);
  83.         puts("------------------------");
  84.         puts("------------------------");
  85.     }while(1);
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement