首页 > 解决方案 > c编程 - 从文件中提取数据字符串

问题描述

我有以下任务:我有一个包含 5 个字符串的文件(卡):

U98_25984nhdrwedb \n
U98_5647BGFREdand \n
U98_30984bgtjfYTs \n
U77_76498375nnnnn \n
U98_83645bscdrTRF \n

我需要将image.txt那些以 . 开头的字符串提取到另一个文件中"U9"。下面没有内存分配的代码(malloc,calloc)将代码正确打印到屏幕上,但它不会将正确的数据打印到image.txt我只得到"98_25984nhdrwedb@". 我认为我错误地应用了内存分配,但是当我使用mallocor calloc(在 while 循环之前)它变得更糟并打印出垃圾,我无法弄清楚如何正确设置它。

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdint.h>
    
typedef uint8_t  BYTE;
    
int main()
{
    FILE *input_card = fopen("card","r");    //open the file for reding
    BYTE data[18];
    int i, n = 5;

    FILE* output = fopen("image.txt","w");    //open the output file for writing

    output = malloc(sizeof(data)*18);         //assign memory
    while (!feof(input_card))
    {
        for (i = 1; i <= n; i++)
        {
            fread(data,sizeof(BYTE),18,input_card);
            if(data[i] != 0)
            {
                if (data[0] == 'U' && data[1] == '9')
                {   
                    printf("data: %s",data);
                    fwrite(&data[i],sizeof(BYTE),18,output);
                }
                fclose(output);
            }
        }
    }
    fclose(input_card);
    free(output);
    return 0;
}

标签: c

解决方案


在您的代码中的以下两行中,第二行不正确:

FILE* output = fopen("image.txt","w");    //open the output file for writing
output = malloc(sizeof(data)*18);         //assign memory <= This is WRONG

变量output是一个FILE指针。您不应该使用malloc. 只有在成功返回它时才应该使用它fopen,这意味着它已经被分配了fopen

这意味着你不需要这个:

free(output); // This is also WRONG

因为这已经释放了指针分配的数据:

fclose(output);

推荐阅读