C - FILE IO读取和写入错误
问题描述:
我试图用新字符逐个交换文件中的现有字符。新字符是通过从ASCII码中减去1来操作现有字符而获得的。该文件已经存在与文本,但由于某种原因,我最终得到一个无限循环。我究竟做错了什么?C - FILE IO读取和写入错误
#include <stdio.h>
int main()
{
FILE *fp = fopen("myfile.txt", "r+");
if (fp == NULL)
printf("File cannot be opened.");
else
{
// Used for retrieving a character from file
int c;
// Pointer will automatically be incremented by one after executing fgetc function
while ((c = fgetc(fp)) != EOF)
{
// Decrement pointer by one to overwrite existing character
fseek(fp, ftell(fp)-1, SEEK_SET);
// Pointer should automatically increment by one after executing fputc function
fputc(c-1, fp);
printf("%c\n", c);
}
fclose(fp);
}
return 0;
}
CNC中 我改变的C数据类型从字符为int,但问题仍然存在。但是,我的问题已通过在fputc()调用后添加fseek(fp,0,SEEK_CUR)解决。我相信Jonathan Leffler的评论应该成为一个答案,因为这个问题没有从另一个问题中得到回答。
答
尝试这种
#include <stdio.h>
int main(void){
FILE *fp = fopen("myfile.txt", "r+");
if (fp == NULL) {
printf("File cannot be opened.");
return -1;
}
int c;
long pos = ftell(fp);
while ((c = fgetc(fp)) != EOF){
fseek(fp, pos, SEEK_SET);//In the case of text file Do not operate the offset.
fputc(c-1, fp);
fflush(fp);//To save the output.
pos = ftell(fp);
printf("%c\n", c);
}
fclose(fp);
return 0;
}
[该'fgetc'功能](http://en.cppreference.com/w/c/io/fgetc)返回一个'int'。这是有原因的。我建议你相应地改变你的变量'c'。 –
当你从阅读转变为写作,以及从写作转变为阅读时,你必须定位两者。在fputc()调用之后添加'fseek(fp,0,SEEK_CUR)'。 (为什么?这个标准是这么说的!参见'fopen()'描述'+'模式:但是,输出不应该直接跟随输入,而不需要对fflush函数或文件定位函数('fseek ', 'fsetpos'或'rewind'),并且输入不应该直接跟在输出之后,除非输入操作遇到文件结束,否则不会对输入文件进行中间调用 _ –
哎呀,我忘了fgetc返回一个int,我把c的数据类型改为int,但问题仍然存在,但是在fputc()调用后添加fseek(fp,0,SEEK_CUR)实际上解决了我的问题。 – Gizdich