Easy Tutorial
❮ C Exercise Example35 C Standard Library Float H ❯

C Exercise Example 97

C Language Classic 100 Examples

Title: Input some characters from the keyboard and write them to disk one by one until a # is entered.

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE* fp = NULL;
    char filename[25];
    char ch;
    printf("Enter the name of the file you want to save to:\n");
    gets(filename);
    if ((fp = fopen(filename, "w")) == NULL)
    {
        printf("error: cannot open file!\n");
        exit(0);
    }
    printf("Now you can enter some characters to save, end with #:\n");
    getchar();
    while ((ch = getchar()) != '#') {
        fputc(ch, fp);
    }
    fclose(fp);
    system("pause");
    return 0;
}

The above example outputs the following results when run:

Enter the name of the file you want to save to:
test.txt
Now you can enter some characters to save, end with #:
www.tutorialpro.org
#

C Language Classic 100 Examples

❮ C Exercise Example35 C Standard Library Float H ❯