Does anybody know why my code for error handling in fgets doesn't work? I've been trying to make this work for ages, and still cannot get this to work. What happens is that instead of skipping the line:
Code:
printf("\nInput line too long for buffer\n")
when p_str!=NULL, it prints the string out as well.
Thanks in advance.
Below part of my code (though not all of it):
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSTUDENT 40
#define MAXNAME 20
/*Declaring Function Prototypes*/
int extract (char *copy_str, char *name_str, int length, student_t *s,int *p_index);
int main(void)
{
FILE *readfile;
char str_copy[40];
char str_name[MAXNAME+1];
char *p_str;
int i;
student_t s [MAXSTUDENT];
int num=0;
int result,index;
char *p_error;
if((readfile=fopen("datafile.txt","rt"))==NULL)
{
printf("Error, unable to read file. Program exiting");
return (1);
}else
{
for(index=0;((p_error=fgets(str_copy,sizeof(str_copy),readfile))!=NULL);index++)
{
if((p_str=strchr(str_copy,'\n'))!=NULL)
{
*p_str='\0'; /*fgets may not read \n, because data might me overwritten*/
result=extract(str_copy,str_name,MAXNAME,s,&index);
} else
{
printf("\nInput line too long for buffer\n"); //This line is printed out when p_str!=NULL
exit(0);
}
}
if(p_error==NULL){
printf("Error in reading file"); /*EOF error*/
}
}
fclose(readfile);
return (0);
}