c - 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@"
. 我认为我错误地应用了内存分配,但是当我使用malloc
or 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;
}
解决方案
在您的代码中的以下两行中,第二行不正确:
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);
推荐阅读
- c# - 从一个word文档复制到另一个word文档
- python - Python sqlite3占位符,用于任意长度值的元组
- python - 在 unet 架构中使用自定义权重图的正确方法
- symfony - 带有自定义标签的 Symfony 的 Select2
- c# - c# httpclient 授权标头对我不起作用?
- php - 覆盖来自不同控制器的数组元素 [Codeigniter]
- html - 是否必须将所有内容(即使只是一列)放在行内?
- java - Java - 写return“”是什么意思;在一个方法?
- python - 如何使用pyvmomi获取vm子文件夹对象部署虚拟机
- amazon-web-services - TeamCity 代理 - AWS CLI