从文件读取并存储在C中

亚历克斯·科恩豪瑟(Alex Kornhauser)

我试图读取一个字符串后跟一个数字的文本文件,然后存储它的内容。到目前为止,如果格式正确,我只能将其打印出来(仅打印字符串(或仅读取int或同时读取两者))。如何跳过空白或格式错误的行(当前与上一行重复)并存储结果?

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

#define MAX_LINE_LENGTH 400

int main ()
{
    char input[MAX_LINE_LENGTH];
    char name[MAX_LINE_LENGTH];
    int number;

    FILE *fr;
    fr = fopen ("updates.txt", "r");
    if (!fr)
    return 1;  
    while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
    {
        /* get a line, up to 200 chars from fr.  done if NULL */
        sscanf (input, "%s", name);
        /* convert the string to just a string */
        printf ("%s\n", name);
    }
    fclose(fr);
    return 0;
}

示例文本文件

寒冷5 
10火焰

狗狗4

火焰11
寒冷6
奇拉格·德赛(Chirag Desai)

下面的代码为您的问题提供了可能的解决方案。

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

#define MAX_LINE_LENGTH 400

int main ()
{
    char input[MAX_LINE_LENGTH];
    char name[MAX_LINE_LENGTH];
    char namet[MAX_LINE_LENGTH];
    int number;

    FILE *fr;
    fr = fopen ("updates.txt", "r");
    if (!fr)
    return 1;
    while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
    {
        memset(name, 0, MAX_LINE_LENGTH);
        memset(namet, 0, MAX_LINE_LENGTH);
        /* get a line, up to 200 chars from fr.  done if NULL */
        //sscanf (input, "%s %d", name, &number);
        sscanf (input, "%s %s", name, namet);

        // TODO: compare here for name shall only contain letters A-Z/a-z
        // TODO: compare here for namet shall only contain digits

        // If both above condition true then go ahead
        number = atoi(namet);

        if(name[0] != '\0')
        {
                /* convert the string to just a string */
                printf ("%s %d\n", name, number);
                //printf ("%s %s\n", name, namet);
        }
    }
    fclose(fr);
    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++:读取定界文件并存储在结构中

C ++从txt文件中读取getline并存储到字符串数组中

读取数字文本文件,并存储在C ++中的整数数组中

从文件中读取数据并存储到结构数组中

从文件中读取整数并存储在数组中

C#:如何停止循环遍历csv文件中的数据并存储上次读取的值

读取文件以删除空格并存储在数组中

BASH读取txt文件并存储在数组中

Bash从文件读取并存储到MATLAB中的变量

从txt文件读取数据并存储在数据框中

读取csv文件,解析数据并存储在字典中

C ++读取文本文件并存储数据

逐行读取C并存储在数组中

从内存c ++中读取位,移位并存储

读取文件内容并存储为数组

逐行读取文件并存储不同的变量

从文件共享中读取图像路径并存储在表存储中 azure

批处理文件:从目录中读取文件名并存储在阵列中

读取文本文件中的值并存储到 Python 中的数组中

在python中读取复杂的JSON文件并存储在数据框中

如何从excel文件中读取数据并存储到变量中?

从文件中读取数字并存储到二维数组中

从 csv 文件读取数据并存储到数组中,我的文件正确打开但文件读取不正确

以特定模式读取csv文件并存储在地图或2D数组中

如何从一个文本文件,并存储读取到Java中的数组

如何读取csv文件到特定行并存储在变量中

无法从文本文件读取并存储到字符串中

从文本文件读取并存储在字符串中

读取多个文件,搜索字符串并存储在列表中