Using fgets() with char* type

后端 未结 3 921
傲寒
傲寒 2021-01-12 15:17

I have a simple question about using fgets() with char* string.

....
char *temp;
FILE fp=fopen(\"test.txt\", \"r\");

fgets(temp, 500, fp);
printf(\"%s\", te         


        
3条回答
  •  时光取名叫无心
    2021-01-12 16:01

    When we write

    char *temp ; 
    

    it means temp is an uninitialized pointer to char i.e. currently it does not contain any address in it .

    While using fgets you have to pass a string in which the bytes read from file pointer is to be copied . link since the temp is uninitialized , the fgets looks like this

    fgets( , 500 , fp ) ;
    

    which is invalid .

    Hence , we should give initialized string which can be formed as :

    1) char *temp = malloc(sizeof(500)) ;
    or
    2) char temp[500] ;
    

    Hence if we pass initialized string to fgets , it would look like

    fgets( < some string > , 500 , fp) ;
    

提交回复
热议问题