fgets doesnt get the last character

use*_*696 2 c string file-io fgets char

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.

ps我很确定字符串的长度不是问题,因为即使我将它更改为2个字符它仍然只打印第一个字符(不打印最后一个字符),并且它们都写在同一行.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Yu *_*Hao 5

char *fgets(char * restrict s, int n, FILE * restrict stream);
Run Code Online (Sandbox Code Playgroud)

fgets函数最多读取一个小于nstream指向的流所指定的字符数所指定的字符数s.

换句话说,如果你需要读取mone1字符,n至少mone1 + 1要传入,并确保缓冲区足够.原因是最后fgets会添加尾随\0.