user9817924
user9817924

Reputation:

fprintf wont work with switch/case statement in C++

I have a simple C++ program to store pressed keys in file. What works is prinf to show it in console but fprintf to save it in file won't work. Even fprintf(logx, "TEST"); works only when i delete while cycle.

My code:

int main(){
char c;
FILE *logx;

logx = fopen("mylog2.txt", "w");
fprintf(logx, "TEST");

while (true)
    {
    Sleep(10);
        for (int i = 8; i <= 255; i++)
        {
            if (GetAsyncKeyState(i) == -32767)
            {
                switch(i) {
                case 96:
                    fprintf(logx, "%d", 0);
                    break;
                case 97:
                    fprintf(logx, "%d", 1);
                    break;
                case 98:
                    fprintf(logx, "%d", 2);
                    break;
                case 99:
                    fprintf(logx, "%d", 3);
                    break;
                case 100:
                    fprintf(logx, "%d", 4);
                    break;
                case 101:
                    printf("%d", 5);
                    break;
                case 102:
                    printf("%d", 6);
                    break;
                case 103:
                    printf("%d", 7);
                    break;
                case 104:
                    printf("%d", 8);
                    break;
                case 105:
                    printf("%d", 9);
                    break;
                default:
                    c = char(i);
                    printf("%c", c);
                    break;
                }
            }
        }
    }

    return 0;
}

File is empty after pressing all possible numbers. Not even TEST is written in file (when while cycle is deleted "TEST" is printed).

Thanks for any help or hint.

Upvotes: 0

Views: 401

Answers (1)

Johannes Overmann
Johannes Overmann

Reputation: 5161

You must terminate the loop somehow. If you terminate your program with Ctrl-C the FILE I/O buffers will not be flushed and your file will be empty.

Alternatively you can put an fflush(logx); behind every individual fprintf() statement to force the data out to the file. But this is only a last resort as it makes file I/O very slow.

You should also close the file after the loop:

fclose(logx);

Upvotes: 1

Related Questions