Вопрос

I have the following code in C to make an input file using an existing input file, but without newlines:

int main()
{
    int T;
    char c;
    FILE *fi,*fo;
    fi=fopen("Square-practice.in","r");
    fo=fopen("Square-practice-a.in","w");

    fscanf(fi,"%d",&T);
    fprintf(fo,"%d",T);
    while(fscanf(fi,"%c",&c)==1){
        if(c=='\n') printf("qwert");
        else    fprintf(fo,"%c",c);
    }

    return 0;
}

There is no compiling error.

However, the output file is exactly the same as the input file, with the newline included. "qwert" is printed 8 times (same as the number of newlines in file fi). So why doesn't the "else" work?

The compiler is MinGW.

Both the fi,fo files are here

Это было полезно?

Решение 3

I'm running this on my Linux and I'm getting just what I should be getting: the same file without new line characters and "qwert" printed to stdout. If you're getting something else, it must be an issue with CR/LF translation. Try replacing "r" and "w" with "rt" and "wt", respectively.


Two PS comments:

  1. The given program works (with or without "rt") on my gcc 4.7.2 on Linux, provided that line terminators in the input file are converted from CRLF to LF. This is reasonable when you move a text file from Windows to Linux and can be done, e.g., with the fromdos tool.

  2. It is true that the C standard (section 7.19.5.3, p. 271, for ISO C99, or section 7.21.5.3, p. 306, for ISO C2011) does not require "t" for text files (so, conforming implementations need not implement it), but it seems that some implementations work differently.

Другие советы

I think you have '\r\n' instead of '\n'. So try

int main()
{
    int T;
    char c;
    FILE *fi,*fo;
    fi=fopen("Square-practice.in","r");
    fo=fopen("Square-practice-a.in","w");

    fscanf(fi,"%d",&T);
    fprintf(fo,"%d",T);
    while(fscanf(fi,"%c",&c)==1){
        if(c=='\n' || c=='\r') printf("qwert");
        else    fprintf(fo,"%c",c);
    }

    return 0;
}

You can also use fgetc() and fputc(). Just skip any \r or \n before passing each char into new file:

Your code with modifications:

int main()
{

    int T;
    int iChr
    char c;
    FILE *fi,*fo;
    fi=fopen("Square-practice.in","r");
    fo=fopen("Square-practice-a.in","w");

    //fscanf(fi,"%d",&T);
    //fprintf(fo,"%d",T);
    iChr = fgetc(fi)
    while(iChr != EOF)
    {
        if((iChr =='\n')||(iChr =='\r')//skipping new file
        {
             printf("qwert");
        }
        else   fputc(fo);//no \n or \r, put in new file
    }
    fclose(fi);        
    fclose(fo);

    return 0;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top