文本文件到已排序的二进制文件,C语言

问题描述 投票:-1回答:1

我们被要求按字母顺序对文本文件的内容(在本例中为R.name)进行排序,并将其写入二进制文件而不将其保存到数组中。到目前为止我所做的只是将文本文件的所有内容写入二进制文件,但我不知道如何在二进制文件中正确排序。我们被告知我们可以使用插入排序,但我不知道如何排序二进制文件,不知道里面的结构数量。

text File []和bin File []分别是文本文件和二进制文件的名称

void textToBinary(char textFile[], char binFile[])
{
FILE * fp;
FILE * fp2;
char ch;
String20 dump;
int i;
structRecipe R;
long int npos;

if( (fp = fopen (textFile, "r")) != NULL)
{   
if((fp2 = fopen (binFile, "wb"))!= NULL)
{

while( fgets(R.name, 21, fp) != NULL)
{
R.name[strlen(R.name) -1] = '\0';
fscanf(fp, "%d%c%s%c", &R.nServings, &ch, R.classifications, &ch);
fscanf(fp, "%s%c%d%c", dump, &ch, &R.nIng, &ch);    

for(i=0; i<R.nIng; i++)
{
fscanf(fp, "%f%c%s%c", &R.Ingredients[i].quantity, &ch, 
R.Ingredients[i].unit, &ch);
fgets(R.Ingredients[i].item, 21, fp);
R.Ingredients[i].item[strlen(R.Ingredients[i].item) - 1] = '\0';
}

fscanf(fp, "%s%c%d%c", dump, &ch, &R.nSteps, &ch);

for(i=0; i< R.nSteps; i++)
{
fgets(R.steps[i], 71, fp);
}

fscanf(fp, "%c", &ch);
fseek(fp2, 0, SEEK_END);
fwrite(&R, sizeof(structRecipe), 1, fp2);

}
fclose(fp2);
}
fclose(fp);
}
else printf("Error opening file for reading \n");
}
`

我是否可以只想到如何排序它而不将二进制文件的内容保存到数组中? (使用c语言)

c sorting text-files structure binaryfiles
1个回答
0
投票

插入排序可能如下所示:

structRecipe R, tR, *pR[2];
int x, written=0;

pR[0]=&R;
pR[1]=&tR;

            ... fill R....
            fscanf(fp, "%c", &ch);

            fseek(fp2, 0, SEEK_SET);
            x=0;
            for(j=0; j<written; j++) {
                fread(&tR, sizeof(structRecipe), 1, fp2);
                if(strcmp(R.name, tR.name)<0) {
                    fwrite(&R, sizeof(structRecipe), 1, fp2);
                    x=!x;
                    break;
                }
            }
            for(; j<written; j++) {
                fread(pR[!x], sizeof(structRecipe), 1, fp2);
                fseek(fp2, -sizeof(structRecipe), SEEK_CUR);
                fwrite(pR[x], sizeof(structRecipe), 1, fp2);
                x=!x;
            }
            fwrite(pR[x], sizeof(structRecipe), 1, fp2);
            written++;

        }
        fclose(fp2);

对不起,这是未经测试的,只是一个想法。

© www.soinside.com 2019 - 2024. All rights reserved.