Harini wrote:
Ive written this sample code in Dev C++ and use fgets to read from a
external file. My compiler crashes with a windows error. Could somebody
help me out
You probably fail to open the file.
a sample of the usage of of fgets in my code is listed below
See the embedded comments:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *fd;
char line[200];
int count = 0;
char *tmp;
int zip = 0;
int uzip = 0;
printf("\nPlease enter your zip code : ");
scanf("%d", &uzip);
/* mha: Please note that you need a call to fflush() after your
prompt and that there is no reason to expect a US zip code to fit
in an int */
uzip = uzip / 100;
printf("uzip = %d", uzip);
fd = fopen("c://Dev-Cpp/SA/STANDARD-SAMPLE1.csv", "r");
/* mha: Nowhere in your code do you check that the above succeeded.
That means that it is quite possible that fd is NULL in the fgets
call below. */
while (fgets(line, 200, fd) != NULL) {
/* mha: While the above may work fine, it is usually better to
use something like 'sizeof line' rather than a hard-coded
number like '200'.
Others will disagree, but I find the superfluous comparison
(!= NULL) a little jarring; those others will find leaving it
out just as stylistically flawed. */
tmp = strtok(line, ",");
zip = atoi(tmp);
/* mha: it is probably better to stick with the strto* family,
since the ato* has much worse error-handling and does not give
you a pointer to the end of the field. */
printf("zip=%d\n", zip);
count++;
}
printf("# lines=%d", count);
/* mha: Even though C99 allows you to fall off the end of main, (1) I
doubt you have a C99 compiler and (2) it is bad practice not to
explicitly return values from functions that return values, as
main does. */
}