Search code examples
cfileline-breaksspacesfgetc

reading a file one character at a time with spaces


I'm trying to convert the case from a file and write into another. The file I'm trying to convert has spaces and a few lines. The converted form is written with no spaces and no line breaks. Does anyone know how I can alter my code, so that it includes the spaces and line breaks from the original file?

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

int main(void)
{
FILE *fp1, *fp2;
fp1 = fopen("exercise2.txt", "r");
fp2 = fopen("exercise2_converted.txt", "w");

int singleline;

if (fp1 == NULL)
{
    printf("Error opening fp1!\n");
    return 0;
}
if (fp2 == NULL)
{
    printf("Error opening fp2!\n");
    fclose(fp1);
    return 0;
}

do
{
    singleline = fgetc(fp1);
    if (islower(singleline))
    {
        singleline = toupper(singleline);
        fputc(singleline, fp2);
    }
    else if (isupper(singleline))
    {
        singleline = tolower(singleline);
        fputc(singleline, fp2);
    }
} while (singleline != EOF);


fclose(fp1);
fclose(fp2);

return 0;
}

Solution

  • Overall beginner's solution:

    ...
    do
    {
        singleline = fgetc(fp1);
        if (singleline == EOF)
          break;        // end of file => game over quit loop immediately
    
        // convert char if neessary
        if (islower(singleline))
        {
            singleline = toupper(singleline);
        }
        else if (isupper(singleline))
        {
            singleline = tolower(singleline);
        }
    
        // output the char
        fputc(singleline, fp2);
    } while (1);
    ...
    

    There are shorter solutions, but these are harder to read and to understand for beginners.