I’m trying to read multiple files. The format of the files would something similar toYYYY-mm-dd-HH-MM.txt and for example 2012-11-26-18-50.txt
I have the following code
char text_buffer[1000];
char file_buffer[256];
int year, month, day, hour, minute;
year = 2012; month = 11; day = 26; hour = 18; minute = 0;
sprintf(file_buffer, "%d-%d-%d-%d-%d.txt", year, month,day,hour,minute);
FILE *ptr_file;
ptr_file=fopen(file_buffer, "r");
if(ptr_file != NULL)
printf("File opened %s for reading.\n", file_buffer);
else
printf("Couldn't open %s.\n", file_buffer);
line_number = 0;
while(fgets(buffer,sizeof(buffer), ptr_file) != NULL){
if(strcmp(buffer, "")==0)
return 0;
char *views = strok(buffer, ",");
...
}
I’m assuming that’s all the information needed. I’ll post all of it if it’s still unclear as to where my problem is.
When I run the program. I get both
Filed opened... and Couldn't open.... then a segmentation fault.
Can someone help me figure this out?
Thanks.
First you will want to make sure you do something (maybe return an error code) when you cannot open the file. A segmentation fault will occur when trying to read from a NULL FILE*.
Also, you are corrupting memory since file_buffer is pointer, not a buffer. You need to initialize it to something. Lastly, you want to make sure you close the file you open.
I am also assuming you define buffer somewhere. In your code example I don’t see the definition. Maybe you meant to use text_buffer instead?
If you are working with LINUX for these types of memory corruptions I would suggest two tools.
These two tools, once you are proficient with them, can help eliminate most simple programming errors.