c - fseek() and ftell() fail in a loop -
i need loop trough directory, data
, read each file, meets conditions, in string , it. reason fails after fseek
call (the output name of first file in directory).
any idea doing wrong?
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> void doalgorithm(char *input) { printf("%s\n", input); } int main(int argc, char** argv) { struct dirent *dir; dir *d = opendir("data"); file *file; while ((dir = readdir(d)) != null) { if (strlen(dir->d_name) > 6 && dir->d_name[6] == 'i') { printf("filename: %s\n", dir->d_name); file = fopen(dir->d_name, "r"); fseek(file, 0, seek_end); long length = ftell(file); fseek(file, 0, seek_set); printf(", filesize: %ld\n", length); char *buffer = malloc(length + 1); fread(buffer, 1, length, file); buffer[length] = '\0'; fclose(file); doalgorithm(buffer); } } closedir(d); return (exit_success); }
your problem file = fopen(dir->d_name, "r");
doesn't know file in directory. need give full path. can this;
struct dirent *dir; // put directory path here. on windows \ instead of / char *path = "/users/adnis/clion/stackoverflow/testdir"; char *slash = ""; dir *d = opendir(path); file *file; while ((dir = readdir(d)) != null) { if (strlen(dir->d_name) > 6 && dir->d_name[6] == 'i') { printf("filename: %s\n", dir->d_name); int length = strlen(path); /*check if path contains '/' @ end before joining filename directory*/ if(path[strlen(path)-1] != '/'){ //on windows '\' slash = "/"; } length += strlen(dir->d_name)+2; // allocate memory new path // , make sure have enough memory. char *newpath = malloc(length); assert(newpath != null); snprintf(newpath,length,"%s%s%s",path,slash,dir->d_name); file = fopen(newpath, "r"); if(file == null){ fprintf(stderr, "fopen: %s\n", strerror(errno)); break; } fseek(file, 0, seek_end); long len = ftell(file); fseek(file, seek_set, 0); char *buffer = malloc(len + 1); fread(buffer, 1, len, file); buffer[strlen(buffer)] = '\0'; printf("%s \n",buffer); fclose(file); } } closedir(d); return (exit_success);
i suggest when reading directory have try , avoid reading "." , ".." since current directory , previous directory. help. in while loop
if(strcmp(dir->d_name,".") == 0 || strcmp(dir->d_name,"..") == 0) continue;
Comments
Post a Comment