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

时间:2015-02-27 19:25:59

标签: c file-io

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

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

1 个答案:

答案 0 :(得分:1)

在调用函数之前,您需要声明函数,在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);
相关问题