【发布时间】:2021-12-16 11:40:58
【问题描述】:
我有一个名为 datafile.data 的输入文件,如下所示:
1,2,1,1,0
1,3,1,1,0
1,1,2,2,1
2,1,2,2,1
2,3,2,3,1
1,1,2,3,2
3,1,1,4,2
2,1,3,2,2
3,3,3,1,2
2,2,3,4,2
这里的第 4 列代表 4 个属性值,例如 A1、A2、A3、A4。最后一列代表类值。对于这个特定的示例文件,有 4 个属性,但对于其他一些文件,可以有“n”个属性,但对于每个文件,最后一列将给出类值。
现在我想将此文件转换为另一个名为:outputfile.exp的文件
输出文件的第一行如下所示:
<Number of rows in the .data file> <Number of attributes> <Max value of A1> <Max value of A2> <Max value of A3> <Max value of A4> <(Max value of last column)+1>
并且输出文件的其余行将与数据文件相同,只有一个变化,即最后一列的每个值都将增加1。
例如,上述示例的输出文件如下所示:
10 4 3 3 3 4 3
1,2,1,1,1
1,3,1,1,1
1,1,2,2,2
2,1,2,2,2
2,3,2,3,2
1,1,2,3,3
3,1,1,4,3
2,1,3,2,3
3,3,3,1,3
2,2,3,4,3
其中第一行的 10 是行数,4 是存在的属性数,(3,3,3,4) 这 4 是属性 A1,A2,A3 和 A4 的最大值,最后 3 代表最高等级价值+1。最后一列的 each 值也增加了 1。
下面我附上我的尝试:
#include <stdio.h>
#include <string.h>
#define MAX_FILE_NAME 100
int main()
{
FILE *fp;
int count = 0; // Line counter (result)
char filename[MAX_FILE_NAME], dataToBeRead[50];
char c; // To store a character read from file
// Open the file
fp = fopen("datafile.data", "r");
// Check if file exists
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
// Extract characters from file and store in character c
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
count = count + 1;
fclose(fp);
printf("%d\n",count);
fp = fopen("datafile.data", "r");
if ( fp == NULL )
{
printf( "Failed to open." ) ;
}
else
{
while( fgets ( dataToBeRead, 50, fp ) != NULL )
{
printf( "%s" , dataToBeRead ) ;
}
fclose(fp) ;
}
return 0;
}
我得到以下输出:
10
1,2,1,1,1
1,3,1,1,1
1,1,2,2,2
2,1,2,2,2
2,3,2,3,2
1,1,2,3,3
3,1,1,4,3
2,1,3,2,3
3,3,3,1,3
2,2,3,4,3
现在我无法继续进行,因为我对 C 非常陌生,请帮助我。
编辑1:示例的输出格式为:
10 4 3 3 3 4 3
1 2 1 1 1
1 3 1 1 1
1 1 2 2 2
2 1 2 2 2
2 3 2 3 2
1 1 2 3 3
3 1 1 4 3
2 1 3 2 3
3 3 3 1 3
2 2 3 4 3
【问题讨论】:
-
如果可以将元数据放在文件的末尾会容易很多。如果您想在开始时编写它,则需要读取两次数据或将其全部存储。
-
我需要在开头写它以匹配特定的模式。所以我不能把它放在最后。
-
您只需要数据,还是正在寻找在 C 中执行此操作的学习练习?您可能需要认真考虑在文件末尾写入元数据,然后编写另一个程序将该行移到开头。让事情尽可能简单。
-
老实说我需要这个,因为我正在使用基于规则的分类器,所以我需要将此输入转换为通用输出格式。格式看起来与我在问题中所说的完全相似。所以我需要输出文件顶部的这些数据。我只想将 .data 文件作为命令行参数,它将生成该格式的输出文件。