Advertisement
alexarcan

print_data_from_multiple_files.c

Nov 3rd, 2015
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<ctype.h>
  4. #include<stdlib.h>
  5. #include<unistd.h>
  6. #include<sys/types.h>
  7. #include<sys/stat.h>
  8. #include<sys/dir.h>
  9. #include<dirent.h>
  10. #include<fcntl.h>
  11.  
  12. void printInFile(char *file, char *buff)
  13. {
  14. int fis = open(file, O_WRONLY | O_APPEND);
  15. if(fis == -1)
  16. {
  17. printf("Error on printfile open\n");
  18. exit(1);
  19. }
  20. write(fis,buff,strlen(buff));
  21.  
  22. close(fis);
  23. }
  24.  
  25. void readFile(char* file, char *buff)
  26. {
  27. int fis = open(file, O_RDONLY);
  28. if(fis == -1)
  29. {
  30. perror("Error on readfile open!\n");
  31. exit(1);
  32. }
  33.  
  34. int myRead;
  35. int nspaces=0, ndigits=0;
  36.  
  37. while((myRead = read(fis, buff, 100)) > 0)
  38. {
  39. int i;
  40. for(i=0;i<myRead;i++)
  41. {
  42. if(buff[i] == ' ')
  43. nspaces++;
  44.  
  45. if(isdigit(buff[i]))
  46. ndigits++;
  47. }
  48. }
  49.  
  50. char str[100];
  51. sprintf(str," has %d spaces, %d digits.\n",nspaces,ndigits);
  52. printInFile("output.txt",str);
  53.  
  54. close(fis);
  55. }
  56.  
  57. void getDataFromDir(char *dirName)
  58. {
  59. char buff[100];
  60. char Path[100];
  61. DIR *dir;
  62. struct stat fileStat;
  63. struct dirent *entry;
  64.  
  65. dir = opendir(dirName);
  66. if(dir==NULL)
  67. {
  68. perror("opendir");
  69. exit(1);
  70. }
  71.  
  72. while( (entry = readdir(dir)) !=NULL)
  73. {
  74. //printf("%s\n",entry->d_name);
  75.  
  76. if( (strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") ==0) )
  77. continue;
  78.  
  79. sprintf(Path,"%s/%s",dirName, entry->d_name);
  80.  
  81. if((stat(Path,&fileStat)) == 0)//ok
  82. {
  83. printf("Calea fis este: %s\n",Path);
  84.  
  85. if(S_ISREG(fileStat.st_mode))
  86. {
  87. //printf("Fisierul: %s\n\n",entry->d_name);
  88. sprintf(buff, "%s ", Path);
  89. printInFile("output.txt", buff);
  90. readFile(Path, buff);
  91. }
  92.  
  93. if(S_ISDIR(fileStat.st_mode))
  94. {
  95. getDataFromDir(Path);
  96. }
  97. }
  98. }
  99.  
  100. }
  101.  
  102. int main(int argc, char *argv[])
  103. {
  104. if(argc < 2)
  105. {
  106. printf("Error, correct usage: directory_name output_file_name\n");
  107. exit(1);
  108. }
  109.  
  110. getDataFromDir(argv[1]);
  111.  
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement