Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C中每3个字符后添加一个换行符?_C_File_Newline - Fatal编程技术网

如何在C中每3个字符后添加一个换行符?

如何在C中每3个字符后添加一个换行符?,c,file,newline,C,File,Newline,我有一个包含以下内容的文本文件“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”:

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);
}
void convert1(){
文件*fp,*fq;
int i,c=0;
fp=fopen(“~/123.txt”,“r”);
fq=fopen(“~/file2.txt”,“w”);
如果(fp==NULL)
printf(“打开123.txt时出错”);
如果(fq==NULL)
printf(“打开文件2.txt时出错”);
而(!feof(fp)){

对于(i=0;i,如注释所示,您的
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


我认为你应该在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++;
}

我现在无法测试它,可能有一些错误,但你明白我的意思。

而(!feof(fp))
是。@melpomene你能详细说明一下吗?@Sebi:仔细阅读它的作用,然后进一步阅读并思考其含义。如果没有帮助,请阅读由melpomene链接的问答。