I have been looking into this for a while and cannot figure it out.
I have the following code and a test.txt file with 10 data points:
int main(){
//opening file for reading ("r").
char *filename;
printf("Please enter file name: ");
scanf("%s", filename);
FILE *file = fopen(filename,"r");
//Counting total number of data points
int ch; //store character reading
while(!feof(file)){
ch = fgetc(file);
if(ch == '\n'){
count++;
}
}
fclose(file);
printf("it is done \n");
printf("%i", count);
If i code it with the filename directly, it works and it successfully counts the 10 data points. However, whenever I try to set it up to scan the filename, once i run it on the terminal and get the message "please enter file name", I write it in, and I always just end up getting "segmentation fault". What am i doing wrong, please help.
>Solution :
This diagnosis is generated with the help of ChatGPT. I did modify the answer to fit into your question.
First, you didn’t declare the count variable used to increment in your while loop.
Second, before you use ‘scanf’ function, you need to allocate memory for the filename pointer
Here’s a modified version of your code:
#include <stdio.h>
int main() {
char filename[100]; // Allocate memory for the filename
int count = 0; // Initialize count to zero
printf("Please enter file name: ");
scanf("%s", filename);
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1; // Exit with an error code
}
int ch; // Store character reading
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') {
count++;
}
}
fclose(file);
printf("Number of lines in the file: %d\n", count);
return 0; // Exit with success code
}
```
In this code:
filenamewas declared with a fixed size (max of 100 chars) to store the file name.- Error-checking cases were added (File== NULL) to ensure the file can be opened successfully.
Countwas declared and initialized to zero.- The
whileloop was modified to read characters until the end of the file (EOF).
This code should correctly count the number of lines in the specified text file. Ensure to include error handling to handle cases where the file might not exist or cannot be opened.