从文件中获取字符串

Tel*_*Vaz 1 c string get file

为什么这段代码的输出是内存中的一些随机字?

void conc()
{
    FILE *source = fopen("c.txt", "r+");
    if(!source)
    {
        printf("Ficheiro não encontrado");
        return;
    }

    short i = 0;
    while(fgetc(source) != EOF)
        i++;

    char tmp_str[i];
    fgets(tmp_str, i, source);
    fclose(source);
    printf("%s", tmp_str);
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该给我文件的内容.

小智 7

因为在使用完文件fgetc()后,位置指示符位于文件末尾.fgets()没有什么可读的.你需要重置它,使它指向开头使用rewind(source);.

顺便说一句,不要使用循环文件fgetc(),这是一个非常难看的解决方案.使用fseek()和/ ftell()lseek()获取文件的大小:

fseek(source, SEEK_END, 0);
long size = ftell(source);
fseek(source, SEEK_SET, 0); // or rewind(source);
Run Code Online (Sandbox Code Playgroud)

替代方案:

off_t size = lseek(source, SEEK_END, 0);
rewind(source);
Run Code Online (Sandbox Code Playgroud)

  • @TelmoVaz欢迎你.顺便说一下,不要遍历文件两次,而是使用`ftell()`. (2认同)