1

Тема: Some misunderstanding in C

Hello everyone!
I have trouble with my C program, shortly speaking it doesn't work correctly and I don't know why.
It deals with text file and it has to replace all capital letters there by lowercase and vice versa...
but when program starts it's loop iterates infinitely and doesn't provide correct result even if I break the loop
artificially...
I suppose that problem concerned with file pointer or maybe there is a special rules for rewriting text files in C..
I've attached C code here so ...any suggestions would be appreciated.
Thanks!

/*The programm converts all uppercase letter in the .txt file to lowercase
and vice versa(e.g. Input: ProGraMMing--->Output: pROgRAmmING************
**************************************************************************/
#include <stdio.h>

int main(){
    FILE *fp;
    char fname[20], ch;
    const char fact = 32;
    puts("Enter a file name");
    gets(fname);
    if ((fp = fopen(fname, "r+")) != NULL){
        while (fscanf(fp, "%c", &ch) != EOF){
            fseek(fp, -1, SEEK_CUR);//move file pointer 1 byte back
            if (ch > 64 && ch < 91){//it's an uppercase letter
                ch += fact;//change to lowercase                
                fputc(ch, fp);
            }
            else if (ch > 96 && ch < 123){//it's a lowercase letter
                ch -= fact;
                fputc(ch, fp);
            }
            else{
                puts("It is not a letter.");
                fseek(fp, 1, SEEK_CUR);//move file pointer to the next character                        
            }
        }//end of while()
        fclose(fp);
    }
    else puts("Error. File cannot be created.");
    return 0;
}

2

Re: Some misunderstanding in C

Some misunderstanding in English. Це україномовний форум.
А вам раджу:
- користуватися стандартними функціями isupper, islower, tolower і toupper;
- не використовувати fscanf, якщо не потрібен форматований ввід (тут цілком достатньо fgetc);
- не користуватися "магічними константами" (порівняйте свій код із ('A' <= ch && ch <= 'Z')).

3

Re: Some misunderstanding in C

Thank you a lot koala for comment!
I will accept your suggestions to my attention.
As for my "wrong" placing comm. I have to say that headline directed me here as place where people (mostly programers) discuss different topics exclusively in English (I thought so)
but anyway I apologize for wrong request

4 Востаннє редагувалося koala (23.10.2016 14:47:05)

Re: Some misunderstanding in C

Check §1.1 of the Rules.