I'm trying to read one line from another file but the program encounters a segmentation fault in the while loop below. What I'm trying to do is count each character in the other file using a while loop to determine the exact size of the line that I want to store in an array. Below is the code:
#include <stdio.h> FILE *fp; char *input = NULL; int ch; int length; int main(void) { fp = fopen("file.txt", "r"); if (fp == NULL) { printf("An Error occurred"); return -1; } while((ch = fgetc(fp)) != '\n' && ch != EOF) { length += 1; } return 0; } The other file has one line that says "Hello World!". Does anyone know why this is happening?
EDIT: As kaylum suggested, I've added an if statement to check the result of opening the file. Even though the file exists, the return value is still NULL when opening it in read mode. Can someone figure this out please?
没有评论:
发表评论