我正在尝试将文件中的现有字符逐个换成新字符。通过从ASCII代码中减去一个来操纵现有字符来获得新字符。该文件已存在文本,但由于某种原因我最终获得了无限循环。我做错了什么?
#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的数据类型从char更改为int,但问题仍然存在。但是,我的问题已通过在fputc()调用后添加fseek(fp,0,SEEK_CUR)来解决。我相信Jonathan Leffler的评论应该成为一个答案,因为这个问题没有得到另一个问题的回答。
答案 0 :(得分:0)
试试这个
#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;
}