gpt4 book ai didi

文本到二进制转换器的类型冲突?

转载 作者:行者123 更新时间:2023-11-30 19:17:05 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序接受文本文件并将其转换为二进制文件。我已经创建了执行此操作的方法,但是当我将输入和输出文件传递给它时,我收到一些错误:

unix1% gcc -Wall -Wextra main.c
main.c: In function 'main':
main.c:23:3: warning: implicit declaration of function 'txtbin'
main.c:23:8: warning: assignment makes pointer from integer without a cast
main.c: At top level:
main.c:30:7: error: conflicting types for 'txtbin'
main.c:23:10: note: previous implicit declaration of 'txtbin' was here
main.c: In function 'txtbin':
main.c:40:7: error: incompatible types when assigning to type 'struct FILE *' from type 'FILE'
main.c:41:7: error: incompatible types when assigning to type 'struct FILE *' from type 'FILE'
main.c:54:5: warning: implicit declaration of function 'strlen'
main.c:54:14: warning: incompatible implicit declaration of built-in function 'strlen'

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 255
#define MINLEN 0
#define NUMCHAR 1
#define NUMBYTE 4

int main(int argc, char * argv[]){

FILE* txtf;
FILE* binf;

if(argc != 4){
fprintf(stderr, "Check usage");exit(1);
}
if((txtf =fopen(argv[2], "w+"))==NULL){
fprintf(stderr, "Could not open text file: %s\n", argv[2]);exit(1);
}
if((binf =fopen(argv[3], "w+b"))==NULL){
fprintf(stderr, "could not open binary file: %s\n", argv[3]);
}

binf = txtbin(txtf,binf);
//bintxt();

return 0;

}

FILE* txtbin(FILE in, FILE out){
FILE *ifp;
FILE *ofp;
int tmpint = 0;
unsigned char tmpchr = 0;
char tmpstr[MAXLEN];

ifp = in;
ofp = out;

while(fscanf(ifp, "%s \t %i \n", tmpstr, &tmpint) == 2){
tmpchr = strlen(tmpstr);
fwrite(&tmpchr, sizeof(tmpchr), NUMCHAR, ofp);
fwrite(tmpstr, sizeof(tmpstr[0]), tmpchr, ofp);
fwrite(&tmpint, sizeof(tmpint), NUMBYTE, ofp);
}

fclose(ifp);
fclose(ofp);

return ofp;
}

我知道我有一些警告,但我最关心的是让程序输出相应文本文件的二进制文件。

顺便说一句,这是文本文件:

你好32再见56我的 1名称 77是 91安德鲁3

hello   32
goodbye 56
my 1
name 77
is 91
andrew 3

最佳答案

在调用函数之前需要声明该函数,请在 main() 之前添加此声明

FILE* txtbin(FILE in, FILE out);

另外,tmpchr 应该是 size_t 而不是 unsigned char 并且这一行

fwrite(&tmpint, sizeof(tmpint), NUMBYTE, ofp);

正在尝试写入4个整数,而不是1,正确的方法是

fwrite(&tmpint, sizeof(tmpint), 1, ofp);

正确的 txtbin() 签名是

FILE* txtbin(FILE* in, FILE* out);

关于文本到二进制转换器的类型冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com