[Beginner to Taurus Road 7] Switch Background Management for Multiple User Account Logins

Project Requirements

Implement multiple accounts

Project implementation

#include <stdio.h>
#include <string.h>

int main(void) {
    // Define variables to represent user names and passwords
    char name[32];
    char password[16];
    FILE *file;  //Defines a file pointer variable whose name is file
    char line[128];
    char name_tmp[32];
    char password_tmp[16];
    char *ret;

    //Open File
    file = fopen("users.txt", "r");   
    if (!file) {   //Equivalent to file == NULL  
        printf("File Open Failed");
        return 1;
    }

    //Enter user name and password
    while (1) {
        // Enter user name and password
        printf("Please enter a user name:");
        scanf("%s", name);
        printf("Please input a password:");
        scanf("%s", password);

        /*
        if (strcmp(name, "admin") == 0 && 
            strcmp(password, "123456") == 0) {
            break;
        } else {
            printf("Wrong username or password!\n';  
            system("pause");
            system("cls");
        }
        */  

        //Read the account from the file and make a judgment!
        while (1) {
            //Read a line
            ret = fgets(line, sizeof(line), file); //line:  "admin 123456\n"
            if (!ret) {
                break;
            }           
            sscanf(line, "%s %s", name_tmp, password_tmp);
            if (!strcmp(name, name_tmp) && !strcmp(password, password_tmp)) {
                break;
            }
        }

        if (ret) {  //User name and password matched successfully
            break;
        } else {
            printf("ERROR Incorrect username or password!\n");  
            system("pause");
            system("cls");

            fseek(file, 0, SEEK_SET); //Set the position pointer inside the file to the header
        }
    }

    system("cls");

    // Print function menu
    printf("---Switch Background Management---\n");
    printf("1. Create Account\n");
    printf("2. IP Administration\n");
    printf("3. Sign out\n");
    printf("Please select...");

    return 0;
}

Project Exercise

1. Opening fopen file
Function Prototype
#include <stdio.h>
FILE fopen( const char fname, const char mode );
Parameter 1:fname denotes the file name (which can contain path information)
Parameter 2: Open mode
Return value: FILE file pointer,
If the open fails, NULL is returned (that is, 0)

mode Open mode
"r" opens a text file as "read" (read-only)
The difference between "r+" and "r" is the addition of "write"
"rb" opens a binary file as "read" (read-only)
The difference between "rb+" and "rb" is the addition of "write"

"w" creates a text file as "write", overwriting it if it already exists
The difference between "w+" and "w" is the addition of "read"
"wb" creates a binary file as "write"
The difference between "wb+" and "wb" is the addition of "read"

"A" opens a text file as "append at the end". (Write only)
The difference between "a+" and "a" is the addition of "read"
"ab" opens a binary file as "tail append". (Write only)
The difference between "ab+" and "ab" is the addition of "read"

Summary:
Open in 1 to 3 characters.
The first character is r, w, or a
r stands for Read and opens an existing file
w stands for Create, creates a new file, and is able to Write
a means "tail append" and can "write"

b, can only be written in the second place, indicating that a binary file is open
+, can only be written at the end, indicating an additional read or write function

Example

#include <stdio.h>

int main(void) {
    FILE *file;

    //file = fopen("users.txt", "r");
    file = fopen("users1.txt", "r");
    if (file != NULL) {  //NULL is 0
        printf("files users.txt Open Successfully!\n");
    } else {
        printf("files users.txt Failed to open!\n");
    }

    return 0;
}

2.Closing operation of Fclose file

Clean up the buffer and release the file pointer.

Demo

#include <stdio.h>

int main(void) {
    FILE *file;

    file = fopen("users.txt", "a");
    fputs("\nxiaoxiao 123456",  file);

    fclose(file);
    return 0;
}

Special attention:
After writing to a file, it is not written to the file immediately, but to the output buffer of the file!
Only when the output buffer is full, fflush is executed, the fclose function is executed, or the program is finished,
Only then will the contents in the output buffer be written to the file!

3. Read operation of fgetc file

Function prototype:
#include <stdio.h>
int fgetc( FILE *stream );
Return value: When successful, returns the read character, returns the int type (the actual value is a character)
Failed or read to end of file, return EOF (that is -1)

Effect:
Read a character from a document

Example:

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;

    file = fopen("users.txt", "r");

    while ((c = fgetc(file)) != EOF) {  //EOF is -1
        printf("%c", c);
    }

    return 0;
}

4.fputc Write a character to file fputc

Function prototype:
#include <stdio.h>
int fputc( int ch, FILE *stream );

Example:
test.c

#include <stdio.h>

int main(void) {
    FILE *file1;
    FILE *file2;
    char c;

    file1 = fopen("test.c", "r");
    file2 = fopen("test2.c", "w");

    while ((c = fgetc(file1)) != EOF) {  //EOF is -1
        fputc(c, file2);
    }

    fclose(file1);
    fclose(file2);

    return 0;
}

5.fgets reads a string from a file

Review:
I learned in Project 4, String Input.

Function prototype:
#include <stdio.h>
char fgets( char str, int num, FILE *stream );
Parameters:
Num: Read up to num-1 characters, or until the end of file EOF (i.e.'File Read Finished')
Returns a value; returns NULL if read fails,
Return str when read is successful

Example:

#include <stdio.h>

int main(void) {
    FILE *file1;
    char tmp[64];

    char c;

    file1 = fopen("test.c", "r");

    while (fgets(tmp, sizeof(tmp), file1) != NULL) { 
        printf("%s", tmp);
    }

    fclose(file1);
    return 0;
}

6.fputs Writes a string to the file

Function prototype:
#include <stdio.h>
int fputs( const char str, FILE stream );

Example

#include <stdio.h>

int main(void) {
    FILE *file1;
    FILE *file2;
    char tmp[64];

    char c;

    file1 = fopen("test.c", "r");
    file2 = fopen("test2.c", "w");

    while (fgets(tmp, sizeof(tmp), file1) != NULL) { 
        fputs(tmp, file2);
    }

    fclose(file1);
    fclose(file2);
    return 0;
}

7.fprintf Write Formatted Data in Archive

Function prototype:
#include <stdio.h>
int fprintf( FILE stream, const char format, ... );

Demo:

#include <stdio.h>

int main(void) {
    FILE *file1;
    char name[32];
    int age;
    char c;

    file1 = fopen("info.txt", "w");

    while (1) {
        printf("Please enter the name of the trainee:");
        scanf("%s", name);
        printf("Please enter%s Achievements: ", name);
        scanf("%d", &age);

        fprintf(file1, "Full name:%s\t\t Age:%d\n", name, age);

        printf("Do I need to continue typing? Y/N\n");

        //fflush(stdin);
        while((c=getchar()) != '\n');  //Until you read the carriage return! 

        scanf("%c", &c);
        if (c == 'Y' || c == 'y') {
            continue;
        } else {
            break;
        }
    }

    fclose(file1);
    return 0;
}

8.fscanf formats data in read files

Function prototype:
#include <stdio.h>
int fscanf( FILE stream, const char format, ... );
Return value: Returns the number of data actually read when successful
On failure, return EOF (-1)
Return 0 if match fails

Demo

#include <stdio.h>

int main(void) {
    FILE *file1;
    char name[32];
    int age;
    int ret;

    file1 = fopen("info.txt", "r");

    while (1) {
        ret = fscanf(file1, "Full name:%s Age:%d\n", &name, &age);
        if (ret == EOF) {
            break;
        }

        printf("%s,%d\n", name, age);
    }

    fclose(file1);
    return 0;
}

9.fwrite Writes data into files in binary form

#include <stdio.h>
Int fwrite (const void buffer, //the actual address of the data to be written, that is, the address of the variable)
size_t size, //size of data per "block"
size_t count, //write several pieces of data
FILE stream );

Demo

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file1;
    char name[32];
    int age;
    int ret;

    file1 = fopen("info.txt", "wb");

    printf("Please enter your name: ");
    gets(name);
    printf("Please enter your age: ");
    scanf("%d", &age);

    fwrite(name, sizeof(name), sizeof(char), file1);
    fwrite(&age, 1, sizeof(int), file1);

    fclose(file1);
    return 0;
}


Supplement:
The difference between w and wb
demo of wb

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file1;
    char info[] = "Hello\nWorld";
    int age;
    int ret;

    file1 = fopen("test.txt", "wb");

    fwrite(info,  sizeof(char), strlen(info),  file1);

    fclose(file1);
    return 0;
}


demo of w

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file1;
    char info[] = "Hello\nWorld";   // \n Save Bit\r\n
    int age;
    int ret;

    file1 = fopen("test.txt", "w");

    fwrite(info, strlen(info), sizeof(char), file1);

    fclose(file1);
    return 0;
}


Summary:
On the windows platform,
When opening files in w mode,
If you use fwrite to write data, you will write'\n'as'\r''n'
Save 10 as 1310
Because, on the windows platform, the carriage return character \n in the text file is saved as \r\n
(\n has ASCII code of 10, \r has ASCII code of 13)

When opening files in wb mode,
When using fwrite to write data, encounter'\n'and still write only as'\n'

fread reads data from files in binary form

Function prototype:
#include <stdio.h>
int fread( void buffer, size_t size, size_t num, FILE stream );

Demo

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file1;
    char name[32];
    int age;
    int ret;

    file1 = fopen("student.txt", "rb");

    fread(name, sizeof(name), sizeof(char), file1);
    fread(&age, 1, sizeof(int), file1);

    printf("%s, %d\n", name, age);

    fclose(file1);
    return 0;
}

putw stores an integer in binary form

demo

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file1;
    int data[] = {1,2,3,4,5};
    int i;

    file1 = fopen("test.txt", "w");

    for (i=0; i<5; i++) {
        putw(data[i], file1);
    }   

    fclose(file1);

    return 0;
}

getw reads an integer in binary form

Function prototype:
int getw(FILE *fp)
Return value: Return read value on success
Return -1 on failure.

Demo

#include <stdio.h>

int main(void) {
    FILE *file;
    int value;

    file = fopen("test.data", "rb");
    if (!file) {
        printf("File Open Failed!\n");
        return 1;
    }

    while (1) {
        value = getw(file); 
        if (value == -1 && feof(file)) {
            break;
        }

        printf("%d ", value);
    }

    fclose(file);

    return 0;
}

File Status Check Function

End of feof file

Function prototype:
#include <stdio.h>
int feof( FILE *stream );
Return value: Returns a non-zero value (true) if the specified program has reached the end of the file.

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;

    file = fopen("test.c", "r");

    //While ((c = fgetc (file))!= EOF) {//EOF is -1
    while (!feof(file)) {
        c = fgetc(file);
        printf("%c", c);
    }

    return 0;
}

ferror file read/write error

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;
    int ret;

    file = fopen("test.c", "r");

    fputc('A', file);

    if (ferror(file)) {
        perror("files file An error occurred");
    }

    return 0;
}

Execution results:

Changing "r" to "r+" will not cause errors.

Cleaerr Clear File Error Flag

Function prototype:
#include <stdio.h>
void clearerr( FILE *stream );

Demo

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;
    int ret;

    file = fopen("test.c", "r");

    fputc('A', file);
    if (ferror(file)) {
        perror("files file An error occurred");
    }

    //If you do not clear the file errors, ferror will return a non-zero value (think there are still errors) even if no errors occur later when reading or writing the file.
    clearerr(file);

    c = fgetc(file);
    printf("c=%c\n", c);
    if (ferror(file)) {
        perror("files file An error occurred");
    }

    return 0;
}

ftell gets the current position of the file pointer

Function prototype:
#include <stdio.h>
long ftell( FILE *stream );

Demo

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;
    int ret;
    long  offset;

    file = fopen("test.c", "r");

    offset = ftell(file);
    printf("The current location is: %ld\n", offset);

    fgetc(file);
    offset = ftell(file);
    printf("The current location is: %ld\n", offset);

    fclose(file);

    return 0;
}

File Positioning Function

Note: Files can always be read and written from their current position to the end of the file!

Fseed random positioning

Function prototype:
#include <stdio.h>
int fseek( FILE *stream, long offset, int origin );

Parameter 2:
The offset can be positive or negative.
<0 Offset to header <>
<0 Offset to tail <>

Parameter 3:
SEEK_SET slave start positioning, where parameter 2 must be greater than 0
Current location of SEEK_CUR slave
SEEK_END slave end positioning, where parameter 2 must be small and 0

Demo

#include <stdio.h>

int main(void) {
    FILE *file;
    char c;
    char buff[256];
    int i;

    file = fopen("test.c", "r");

    //Last 10 Characters of Read File
    fseek(file, -10, SEEK_END);
    while (!feof(file)) {
        c = fgetc(file);
        printf("%c", c);
    }

    //Read the first line of the file
    fseek(file, 0, SEEK_SET);
    fgets(buff, sizeof(buff), file);
    printf("\n First line:%s\n", buff);

    //Read the first 10 characters of the current position
    fseek(file, -10, SEEK_CUR);
    printf("\n The ten characters are:");
    for (i=0; i<10; i++) {
        c = fgetc(file);
        printf("%c", c);
    }

    close(file);
    return 0;
}

Rewind rewind

Position the position pointer of the file to the start position.

rewind(file)
Equivalent to:
fseek(file, 0, SEEK_SET)

Project Exercises

1.Exercise 1
Implement project 7 independently.

Write a program that counts how many characters and rows the program itself has and prints the output side by side

#include <stdio.h>

// Count the program itself, how many characters, how many lines of code

int main(void) {
    FILE *file ;
    char c;
    int count_char = 0; //Total number of characters
    int count_line = 0;  //Number of rows

    file = fopen("test.c", "r");
    if (!file ) {
        printf("File Open Failed!\n");
        return 1;
    }

    while ((c=fgetc(file)) != EOF) {
        count_char++;
        if (c == '\n') {
            count_line++;
        }
    }

    count_line++;

    printf("Total %d Characters\n", count_char);
    printf("Total %d Line Code\n", count_line);

    return 0;
}

3. There is already a file to save the address book, assuming the following:

note.txt
 Tel:13507318888 Addr:Wudang
 Liu Bei Tel:13802289999 Addr:Chengdu
 Ma YunTel:13904256666 Addr:Hangzhou
 Ma Huateng Tel:13107551111 Addr:Shenzhen

Write a program that performs as follows:

Reference resources:

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file;
    char name_search[64];
    char line[256];
    char name[64];
    char tel[32];
    char addr[32];
    int found = 0;

    file = fopen("note.txt", "r");
    if (!file) {
        printf("File Open Failed\n");
        return 1;
    }

    printf("Please enter the user name to query:");
    scanf("%s", name_search);

    while (!feof(file)) {
            fscanf(file, "%s Tel:%s Addr:%s\n", name, tel, addr);
            if (!strcmp(name, name_search)) {
                printf("%s The phone number is:%s\n", name_search, tel);
                found = 1;
                break;
            }
    }

    if (found == 0) {
        printf("No,%s Information\n", name_search);
    }

    return 0;
}

Special attention needs to be paid to the last \n in the format string of fscanf, otherwise only the first line can be matched!

Supplementary Notes:

For the following text:
Tel:13507318888 Addr:Wudang
 Liu Bei Tel:13802289999 Addr:Chengdu
 Ma YunTel:13904256666 Addr:Hangzhou
 Ma Huateng Tel:13107551111 Addr:Shenzhen

The following code can be read in a loop:
fscanf(file, "%s Tel:%s Addr:%s\n", name, tel, addr);

But without a carriage return, it can be read using the following statements:
fscanf(file, "%s Tel:%s Addr:%s", name, tel, addr);

This is because:
Using fscanf (file,'%s Tel:%s Addr:%s', name_tmp, tel, addr) to match to the second%s of the first line, matches exactly the first line, except for the last carriage return.The first line now has a carriage return.Then enter the second round of the loop and start using scanf matching again, but note that matching continues from where the last match of the gear ended, that is, until the carriage return at the end of the first line, in this format string, the first is%s, so the carriage return at the end of the first line will be skipped to match successfully.

If the contents of the file are in this format, you must add\n to the end of the format string
 Name: Zhang Sanfeng tel: 13243879188  
Name: Tel. Zhang Sifeng: 13243879199

Summary: Special attention needs to be paid to the role of the last \n in the format string of fscanf.

Keywords: C++ Windows ascii

Added by Yaak on Sat, 21 Dec 2019 00:18:25 +0200