c++ - C语言fseek函数的SEEK_CUR问题
巴扎黑
巴扎黑 2017-04-17 15:06:03
0
1
1160

我在文件中有“NAME”这个单词,我想把它读出来,不用fscanf函数,用一个字符一个字符地读,比如fgetc函数,需要将读文件指针移动,所以我用了fseek函数,想让它向前移动一个位置:

fseek(fp,1,SEEK_CUR);

我最开始时用下面代码,读到了'N'这个字符:

ch=fgetc(fp);
printf("%c",ch);

接下来用fseek函数再往下读,我显示的总是一个'?'字符,没有读出'A'字符,结果如下:

完整代码如下:

#include <cstdio>
#include <cstring>
#include <fstream>
using namespace std;

int main(){
    FILE *fp;
    fp=fopen("test.txt","r+");
    if(fp==NULL){
        printf("there is no character.");
        return 0;
    }
    char ch;
    char test[255];
    ch=fgetc(fp);
    printf("%c",ch);
    fseek(fp,1,SEEK_CUR);
    ch=fgetc(fp);
    printf("%c",ch);
}

...

巴扎黑
巴扎黑

répondre à tous(1)
Ty80
  1. 你不需要 r+

  2. 你不需要 fseek。fgetc 会自动前进文件的当前读取位置

  3. 你的文件是用记事本编辑的吧?你 fseek(fp, 4, SEEK_CUR); 试试?

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!