我的下一個文本文件,我已經閱讀並的所有行然後打印爲什麼不這段代碼打印文件
ADCA SI IMM 89ii 1 1 2
DIR 99dd 1 1 2
EXT B9hhll 1 2 3
IDX A9xb 1 1 2
IDX1 A9xbff 1 2 3
IDX2 A9xbeeff 1 3 4
[D,IDX] A9xb 1 1 2
[IDX2] A9xbeeff 1 3 4
但不是打印整個文件,它打印:
ADCA SI IMM 89ii 1 1 2
EXT B9hhll 1 2 3
IDX1 A9xbff 1 2 3
[D,IDX] A9xb 1 1 2
也有一些線路失蹤,我不明白爲什麼,但如果我在工作正確行的末尾添加一些製表符,我怎麼能解決這個問題,而不\ t ??下面是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 8
typedef enum {INS,OP,DIR,MAQ,CAL,X_CAL,TOTAL} table;
void remove(char *c);
void SearchEndLine(FILE *fd);
void ignoreSpaces(FILE *fd);
char *Operands(FILE *hc12,int table);
int main()
{
int car,i;
FILE *hc12;
char *ins,*op,*dir[MAX],*maq[MAX],*cal[MAX],*x_cal[MAX],*s[MAX];
if((hc12 = fopen("file.txt","r"))!= NULL)
{
i = 0;
while((car = fgetc(hc12))!= EOF)
{
if(car != '\t')
{
ins = Operands(hc12,INS);
printf("%s\t",ins);
ignoreSpaces(hc12);
op = Operands(hc12,OP);
printf("%s\t",op);
ignoreSpaces(hc12);
dir[i] = Operands(hc12,DIR);
printf("%s\t",dir[i]);
ignoreSpaces(hc12);
maq[i] = Operands(hc12,MAQ);
printf("%s\t",maq[i]);
ignoreSpaces(hc12);
cal[i] = Operands(hc12,CAL);
printf("%s\t",cal[i]);
ignoreSpaces(hc12);
x_cal[i] = Operands(hc12,X_CAL);
printf("%s\t",x_cal[i]);
ignoreSpaces(hc12);
s[i] = Operands(hc12,TOTAL);
printf("%s\n",s[i]);
SearchEndLine(hc12);
}
else
{
ignoreSpaces(hc12);
dir[i] = Operands(hc12,DIR);
printf("\t\t%s\t",dir[i]);
ignoreSpaces(hc12);
maq[i] = Operands(hc12,MAQ);
printf("%s\t",maq[i]);
ignoreSpaces(hc12);
cal[i] = Operands(hc12,CAL);
printf("%s\t",cal[i]);
ignoreSpaces(hc12);
x_cal[i] = Operands(hc12,X_CAL);
printf("%s\t",x_cal[i]);
ignoreSpaces(hc12);
s[i] = Operands(hc12,TOTAL);
printf("%s\n",s[i]);
SearchEndLine(hc12);
}
i++;
}
}
return 0;
}
void SearchEndLine(FILE *fd)
{
int car;
while((car = fgetc(fd))!= '\n')
;
}
void ignoreSpaces(FILE *fd)
{
int car;
do
{
car = fgetc(fd);
}while(car == '\t' || car == ' ');
}
char *Operands(FILE *hc12,int table)
{
int car,lon = 0,pos;
char *c;
fseek(hc12,-1,SEEK_CUR);
pos = ftell(hc12);
if((table==INS)||(table==OP)||(table==DIR)||(table==MAQ)||(table==CAL)||(table==X_CAL))
{
do
{
car = fgetc(hc12);
lon++;
}while(car != '\t');
}
else
{
do
{
car = fgetc(hc12);
lon++;
}while(car != '\n');
}
fseek(hc12,pos,SEEK_SET);
c = (char*)calloc((lon+1),sizeof(char));
fgets(c,lon+1,hc12);
remove(c);
return c;
}
void remove(char *c)
{
char *ptr;
if(((ptr=strchr(c,'\n'))!=NULL)||((ptr=strchr(c,'\t'))!=NULL)||((ptr=strchr(c,' '))!=NULL))
*ptr = '\0';
}
你錯過了第二行,所以可能會出現代碼涉及'\ n'的問題。 – moeCake
使用'fgets()'一次獲取一行並對其進行處理將使得更容易解密流。 – chux
'SearchEndLine()'應該檢測EOF以及換行符,以防萬一文件的最後一行不以換行符結束。 –