【问题标题】:C language reading from file and placing in variablesC语言读取文件并放入变量
【发布时间】:2022-12-31 02:57:48
【问题描述】:

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

例子:

Admin:Username Password
How to make?
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++;

    }
}

【问题讨论】:

  • 提示:使用fgets() 阅读整行,然后使用sscanf() 或使用strchr() 甚至strtok() 之类的内容解析该行。有很多可能性,所以您可能只想尝试一下

标签: c file txt


【解决方案1】:

考虑到您在问题中发布的初始要求,文本文件包含以下行:

管理员:用户名密码

将管理员存储在变量type中,用户名存储在变量username中,类似地密码存储在变量Password中。
您可以声明一个 structure 类似于:

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

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

#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
", 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
", user_1.type);
            printf("%s
", user_1.username);
            printf("%s", user_1.password);
            free(line);
        }

        fclose(file);
    }
    return 0;
}

PS:以上实现可能存在一些缺陷/错误,请以上述代码为例。

【讨论】:

    【解决方案2】:

    首先,您可以使用函数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!
    " );
            exit( EXIT_FAILURE );
        }
    
        //read one line of input
        if ( ! read_exactly_one_line( line, sizeof line, fp ) )
        {
            fprintf( stderr, "File is empty!
    " );
            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!
    " );
            exit( EXIT_FAILURE );
        }
    
        //print the first token
        printf( "Type:%.*s
    ", (int)(p - line), line );
    
        //find the delimiter between the second and third token
        q = strchr( line, ' ' );
        if ( p == NULL )
        {
            fprintf( stderr, "Unable to find second delimiter!
    " );
            exit( EXIT_FAILURE );
        }
    
        //move pointer to start of second token
        p++;
    
        //print the second token
        printf( "User:%.*s
    ", (int)(q - p), p );
    
        //move pointer to start of third token
        q++;
    
        //print the third token
        printf( "Pw:%s", 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!
    " );
                exit( EXIT_FAILURE );
            }
    
            return false;
        }
    
        //make sure that line was not too long for input buffer
        p = strchr( buffer, '
    ' );
        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() != '
    ' && !feof(stdin) )
            {
                printf( "Line input was too long!
    " );
                exit( EXIT_FAILURE );
            }
        }
        else
        {
            //remove newline character by overwriting it with a null
            //character
            *p = '
    猜你喜欢
    • 2022-10-07
    • 1970-01-01
    • 2012-02-13
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2011-03-01
    • 2011-12-08
    相关资源
    最近更新 更多