fscanf()只写入输入文件

时间:2017-02-10 02:18:37

标签: c file while-loop fwrite scanf

我正在编写一个代码来将文本文件转换为二进制文件。它没有返回任何错误并运行正常,除了在这个特定的例子中它不打印名字的事实。我的输入文件包含john doe 1 4.0。预期输出为johndoe@▒,但我的输出为doe@▒。我尝试使用fseek移动偏移量。我尝试以不同方式关闭文件。我尝试重命名我的变量并更改if语句。

我不完全确定,但我觉得错误可能来自循环。如果我交换firstName和lastName,同样的事情发生但反转,这意味着我的代码省略了使用fwrite首先读取的内容。我的代码有什么问题导致这种情况发生?

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

void textToBinary(char *inputFile, char *outputFile){

    FILE *ifp, *ofp;

    char firstName[256], lastName[256];
    int sID; 
    float gpa;

    unsigned char firstNameLen = strlen(firstName);
    unsigned char lastNameLen = strlen(lastName);

    if(((ifp = fopen(inputFile, "r")) != NULL)&&((ofp = fopen(outputFile, "w")) != NULL)){
        while((fscanf(ifp, "%s %s %d %f\n", firstName, lastName, &sID, &gpa)) != EOF){
            fwrite(&firstNameLen, sizeof(firstNameLen), 1, ofp);
            fwrite(firstName, sizeof(char), firstNameLen, ofp);
            fwrite(&lastNameLen, sizeof(lastNameLen), 1, ofp);
            fwrite(lastName, sizeof(char), lastNameLen, ofp);
            fwrite(&sID, sizeof(int), 1, ofp);
            fwrite(&gpa, sizeof(float), 1, ofp);
        }
        fclose(ifp);
        fclose(ofp);
    }else{
        fprintf(stderr, "Couldn't open: %s\n", ifp);
    }   
}

1 个答案:

答案 0 :(得分:1)

建议使用上述评论重新编写代码

//unsigned char firstNameLen = strlen(firstName);
//unsigned char lastNameLen = strlen(lastName);

if(((ifp = fopen(inputFile, "r")) != NULL)&&((ofp = fopen(outputFile, "w")) != NULL)){
    while((fscanf(ifp, "%255s %255s %d %f", firstName, lastName, &sID, &gpa)) == 4){
        unsigned char firstNameLen = strlen(firstName);
        unsigned char lastNameLen = strlen(lastName);
        fwrite(&firstNameLen, sizeof firstNameLen, 1, ofp);
        fwrite(firstName, sizeof *firstName, firstNameLen, ofp);
        fwrite(&lastNameLen, sizeof lastNameLen, 1, ofp);
        fwrite(lastName, sizeof *lastName, lastNameLen, ofp);
        fwrite(&sID, sizeof sID, 1, ofp);
        fwrite(&gpa, sizeof gpa, 1, ofp);
    }
    fclose(ifp);
    fclose(ofp);
}else{