c# C语言从文件阅读并放入变量

xyhw6mcr  于 2022-12-31  发布在  C#
关注(0)|答案(2)|浏览(245)

在一个文本文件中,我有一个类型:用户名密码的格式,我如何将它放在三个不同的变量中,以便变量类型在变量类型中,用户名在用户名中,密码在C中的密码中?
示例:

Admin:Username Password

如何制作?

Type:Admin
User:Username 
Pw:Password

下面是我的代码:

int ch;
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
    // Check for the colon character
    if (ch == ':') {
        // We have reached the end of the type string
        // Move to the next variable
        i = 0;
        continue;
    }
    // Check for the space character
    if (ch == ' ') 
    {
        // We have reached the end of the username string
        // Move to the next variable
        i = 0;
        continue;
    }
    // Store the character in the appropriate variable
    if (i < 50) {
        if (type[0] == 0) {
            type[i] = ch;
        } else if (username[0] == 0) {
            username[i] = ch;
        } else {
            password[i] = ch;
        }
        i++;

    }
}
to94eoyn

to94eoyn1#

考虑到您在问题中发布的初始要求,文本文件应包含以下行:
管理员:用户名和密码
将Admin存储在变量type中,将Username存储在变量username中,类似地将Password存储在变量Password中。
你可以声明一个structure,类似于:

typedef struct user {
    char type[512];
    char username[512];
    char password[512];
} user;

正如@IngoLeonhardt评论的那样,strtok()strchr()可用于解析从文本文件读取的行,您可以参考下面的简单示例代码片段来理解并进一步改进逻辑。

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

typedef struct user {
    char type[512];
    char username[512];
    char password[512];
} user;

int main(void)
{
    FILE *file = fopen("test.txt","r");
    char *line = NULL;
    size_t linesize = 0;
    char *token;
    const char colon[2] = ":";
    const char space[2] = " ";
    
    user user_1;
    
    if (file) 
    {
        while (getline(&line, &linesize, file) != -1) 
        {
            printf("%s\n", line);
            
            token = strtok(line, colon);
            memcpy(user_1.type, token, strlen(token));
            
            token = strtok(NULL, space);
            strcpy(user_1.username, token);
            
            token = strtok(NULL, space);
            strcpy(user_1.password, token);
            
            printf("%s\n", user_1.type);
            printf("%s\n", user_1.username);
            printf("%s", user_1.password);
            free(line);
        }

        fclose(file);
    }
    return 0;
}

附言:上面的实现可能有一些缺陷/bug,请把上面的代码作为一个例子来考虑。

3mpgtkmj

3mpgtkmj2#

首先,可以使用函数fgets从文件中读取一行字符串,然后使用函数strchr查找字符串中的分隔符':'' ',找到后,可以使用printf打印各个子字符串。
下面是一个例子:

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

bool read_exactly_one_line( char buffer[], int buffer_size, FILE *fp );

int main( void )
{
    FILE *fp;
    char line[200];
    char *p, *q;

    //open the input file
    fp = fopen( "input.txt", "r" );
    if ( fp == NULL )
    {
        fprintf( stderr, "Error opening file!\n" );
        exit( EXIT_FAILURE );
    }

    //read one line of input
    if ( ! read_exactly_one_line( line, sizeof line, fp ) )
    {
        fprintf( stderr, "File is empty!\n" );
        exit( EXIT_FAILURE );
    }

    //find the delimiter between the first and second token
    p = strchr( line, ':' );
    if ( p == NULL )
    {
        fprintf( stderr, "Unable to find first delimiter!\n" );
        exit( EXIT_FAILURE );
    }

    //print the first token
    printf( "Type:%.*s\n", (int)(p - line), line );

    //find the delimiter between the second and third token
    q = strchr( line, ' ' );
    if ( q == NULL )
    {
        fprintf( stderr, "Unable to find second delimiter!\n" );
        exit( EXIT_FAILURE );
    }

    //move pointer to start of second token
    p++;

    //print the second token
    printf( "User:%.*s\n", (int)(q - p), p );

    //move pointer to start of third token
    q++;

    //print the third token
    printf( "Pw:%s\n", q );

    //cleanup
    fclose( fp );
}

//This function will read exactly one line and remove the newline
//character, if it exists. On success, it will return true. If this
//function is unable to read any further lines due to end-of-file,
//it returns false. If it fails for any other reason, it will not
//return, but will print an error message and call "exit" instead.
bool read_exactly_one_line( char buffer[], int buffer_size, FILE *fp )
{
    char *p;

    //attempt to read one line from the stream
    if ( fgets( buffer, buffer_size, fp ) == NULL )
    {
        if ( ferror( fp ) )
        {
            fprintf( stderr, "Input error!\n" );
            exit( EXIT_FAILURE );
        }

        return false;
    }

    //make sure that line was not too long for input buffer
    p = strchr( buffer, '\n' );
    if ( p == NULL )
    {
        //a missing newline character is ok if the next
        //character is a newline character or if we have
        //reached end-of-file (for example if the input is
        //being piped from a file or if the user enters
        //end-of-file in the terminal itself)
        if ( getchar() != '\n' && !feof(stdin) )
        {
            printf( "Line input was too long!\n" );
            exit( EXIT_FAILURE );
        }
    }
    else
    {
        //remove newline character by overwriting it with a null
        //character
        *p = '\0';
    }

    return true;
}

对于输入

Admin:Username Password

该程序具有以下输出:

Type:Admin
User:Username
Pw:Password

相关问题