Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets doesnt get the last character

for some reason, when I print phrase in the following code I discover that the fgets function doesn't get the last characater in the text file. I already checked mone1 and saw that its given enough space for the text in the file. Does someone have an explanation and a soloution to that occurrence?

Tnx, Dean.

p.s I'm pretty sure the length of the string is not a problem cause even when I'm changing it to 2 characters it's still prints only the first(doesn't print the last char), and it's all written in the same line.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
    printf("ss");
    FILE * sent=NULL;
    FILE * voca=NULL;
    sent=fopen(argv[1],"r");
    voca=fopen(argv[2],"r");
        if(voca==NULL){
        printf("cannot open voca ");
        fclose(voca);
    }
    if(sent==NULL){
        printf("cannot open sent");
        fclose(sent);
    }
    int mone1=0;
    int mone2=0;
    while(EOF!=fgetc(sent))
        mone1++;    
    while(EOF!=fgetc(voca))
        mone2++;    
    fseek(sent,0L,SEEK_SET);
    fseek(voca,0L,SEEK_SET);
    char* phrase=(char*)(malloc(mone1*sizeof(char)));
    char* voc=(char*)(malloc(mone2*sizeof(char)));
    fgets(phrase,mone1,sent);
    fgets(voc,mone2,voca);
    printf("%s",phrase);
    return 0;
}
like image 588
user2559696 Avatar asked Oct 16 '25 23:10

user2559696


1 Answers

char *fgets(char * restrict s, int n, FILE * restrict stream);

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s.

In another word, if you need to read mone1 characters, pass in n as at least mone1 + 1 and make sure the buffer is enough, too. The reason is fgets will add the trailing \0 at the end.

like image 72
Yu Hao Avatar answered Oct 19 '25 11:10

Yu Hao