我有一个文本文件" 123.txt"有了这个内容:
123456789
我希望输出为:
123
456个
789
这意味着,每3个字符后必须插入一个换行符。
void convert1 (){
FILE *fp, *fq;
int i,c = 0;
fp = fopen("~/123.txt","r");
fq = fopen("~/file2.txt","w");
if(fp == NULL)
printf("Error in opening 123.txt");
if(fq == NULL)
printf("Error in opening file2.txt");
while (!feof(fp)){
for (i=0; i<3; i++){
c = fgetc(fp);
if(c == 10)
i=3;
fprintf(fq, "%c", c);
}
if(i==4)
break;
fprintf (fq, "\n");
}
fclose(fp);
fclose(fq);
}
我的代码工作正常,但也会在文件末尾打印换行符,这是不可取的。这意味着,在上面的示例中,在789之后添加换行符。如何防止我的程序在输出文件的末尾添加虚假的换行符?
答案 0 :(得分:2)
如评论中所示,您的while
循环不正确。请尝试使用以下代码交换while
循环:
i = 0;
while(1)
{
// Read a character and stop if reading fails.
c = fgetc(fp);
if(feof(fp))
break;
// When a line ends, then start over counting (similar as you did it).
if(c == '\n')
i = -1;
// Just before a "fourth" character is written, write an additional newline character.
// This solves your main problem of a newline character at the end of the file.
if(i == 3)
{
fprintf(fq, "\n");
i = 0;
}
// Write the character that was read and count it.
fprintf(fq, "%c", c);
i++;
}
示例:包含以下内容的文件
12345
123456789
将变为包含以下内容的文件:
123
45个
123个
456个
789
答案 1 :(得分:0)
我认为你应该在lopp的开始时做你的新行:
// first read
c = fgetc(fp);
i=0;
// fgetc returns EOF when end of file is read, I usually do like that
while((c = fgetc(fp)) != EOF)
{
// Basically, that means "if i divided by 3 is not afloating number". So,
// it will be true every 3 loops, no need to reset i but the first loop has
// to be ignored
if(i%3 == 0 && i != 0)
{
fprintf (fq, "\n");
}
// Write the character
fprintf(fq, "%c", c);
// and increase i
i++;
}
我现在无法测试,也许有一些错误,但你明白我的意思。