函数fgetc无法正常工作

时间:2019-01-27 23:06:32

标签: c file codeblocks

我正在测试fgetc()函数,但无法正常工作(我在此之前已使用此函数,所以我知道它的工作原理)

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

int main()
{
    FILE *file = NULL;
    int n;

    file = fopen("test.txt", "w+");
        if(file != NULL)
        {
            fputs("ab", file);
            printf("%c", fgetc(file));
        }
        else
        {
            printf("error");
        }
    return 0;
}

输出应为“ a”,但其他内容

2 个答案:

答案 0 :(得分:1)

已打开文件以供写入和读取,但是您需要function highlightNoteJustSaved(){ var curI = noteCounter; var anchorAt = parseInt($("#anchorAt").val()); var highlightLen = parseInt($("#highlightLen").val()); /*p to find, for example: p-2-French*/ var curP = document.getElementById('p-'+curSentNum.toString()+"-"+$("#highlightLangName").val()); var range = document.createRange(); root_node = curP; range.setStart(root_node.childNodes[0], anchorAt); range.setEnd(root_node.childNodes[0], anchorAt+highlightLen); var newNode = document.createElement("span"); newNode.style.cssText="background-color:#ceff99";//yellow newNode.className = alreadyNoteStr; newNode.setAttribute('id','already-note-'+curI.toString()); range.surroundContents(newNode); } 到文件中的正确位置(此处是开头)。特别是,在读写之间切换时,您需要fseekfseek

  

指定“ r +”,“ w +”或“ a +”访问类型时,两个   和写入已启用(据说该文件已打开以进行“更新”)。   但是,当您从阅读切换为书写时,输入操作   必须遇到EOF标记。如果没有EOF,则必须使用   介入对文件定位功能的调用。文件定位   函数是fsetpos,fseek和rewind。 从写作切换为   阅读时,您必须使用干预来使您感到困惑或   文件定位功能

在任何情况下,写入文件后,文件指针都位于错误的位置以读取刚刚写入的内容。

所以代码变成了

fflush

如果要继续写入文件,则必须#include <stdio.h> #include <stdlib.h> int main(void) { FILE *file = NULL; file = fopen("test.txt", "w+"); if(file != NULL) { fputs("ab", file); fseek(file, 0, SEEK_SET); printf("%c", fgetc(file)); fclose(file); } else { printf("error"); } return 0; } 结束。

答案 1 :(得分:0)

您的错误是您正在尝试读取已打开以进行写入的文件。您应该在其中写入内容,然后关闭文件并重新打开以进行读取。这段代码将显示我在说什么:

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



int main()
{


    FILE *fileRead, *fileWrite = NULL;
    int n;

    fileWrite = fopen("test.txt", "w+");
        if(fileWrite != NULL)
        {
            fputs("ab", fileWrite);
            fclose(fileWrite);
        }
        else
        {
            printf("error");
        }

    // Open again the file for read
    fileRead = fopen("test.txt", "r");
    printf("%c", fgetc(fileRead));
    fclose(fileWrite);

    // End function
    return 0;
}
相关问题