从fgets中读取的奇怪字符(但不在文件中)

时间:2017-01-23 18:54:28

标签: c io fgets

我正在制作一个程序来从文本文件中检索记录行(records_file.txt)。文本文件存储3列数据(名称,电话,地址)。对于文件中的每个记录行,列值由" |"分隔。

我写的检索记录号的函数有列号(1或2 - 名称或电话)和字段值的参数。该函数从文件中读取每条记录行(使用fgets),添加" |"开始,找到与给定列对应的bar(|)位置。 然后,函数收集条形位置之间的字符,并将其与“'值”进行比较。功能论证。如果匹配,则函数返回当前行号。

该函数几乎可以工作,除了从文件中读取的文本中有异常字符。打开时我在文件中看不到这些字符。试过很多事情,比如(?)重置readbuffer或关闭文件。但问题仍然存在。

端子输出如图所示。字符在" ---- LINE x ----"下面,并在行中显示"字符串行是:%s"。在这种情况下,它们是一个包含"?"但在此之前我也看到了其他人(比如"<"和字母) various chars(not visible in file itself)

我能做些什么来完成这项工作? (我需要(bar)字符串行只有:| test1 | 111 222 333 | 50,sams st etc)

这是txt文件的当前内容:

test fo|222 222 222|53,sams st
test1|111 222 333|50,sams st
test 2|555 666 333|51,sams st
test three|444 777 222|52,sams st

这是代码:

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h> //mkdir
#include <stdio.h> //printf
#include <errno.h> //error number
#include <unistd.h> //access
#include <string.h> //strcat
#include <ctype.h> //isspace
#include <stdlib.h>//malloc

int searchRec(int column, char* value);
int checkFile();

//assumes looking for exact match
//check column 1 or 2
int searchRecord(int column,char* value){
    printf("\n- starting searchRecord function -");
    int returnint = 0; //value to return


    //gates used for getting bar positions
    int g1 =0; //bar 1
    int g2 =0; //bar 2
    int g3 =0; //bar 3

    if(column == 1){
        g1 = 1;
        g2 = 1;
    }else if(column == 2){
        g2 = 1;
        g3 = 1;
    }

    printf("\ngates are: g1:%d g2:%d g3:%d",g1,g2,g3);



    int lineNo = 0; //track line number in file

    int txtexists = checkFile(); //check "records_file.txt" file exists using opendir and access functions
    if(txtexists==1){

        FILE* file = fopen("./data/records_file.txt","r");
        if(file==NULL){ printf("\nfopen error"); returnint = -3; return returnint; }        


        char readbuffer[250] = "";


        while(fgets(readbuffer,250,file)){ //loop through file lines

            printf("\n--------LINE %d-------\n",lineNo);

            //get string segment from column
            char bar[strlen(readbuffer)+1]; //string with | added to start
            bar[0] = '|';
            strcat(bar,readbuffer);         

            printf("\nstring line read from file is - %s", bar);


            int position1 = 0; //first bar index
            int position2 = 0; //second bar index

            int barpos = -1; 
            int pass = 0;
            int i1 = 0; //char index counter

            //loop for position1 and position2 of bars
            for(int i = 0; i < 2; i++){
                printf("\ngetting | %d position",i+1);

                printf("\ni1 cycle(%d) : %d",i,i1);

                //loop through characters of (bar)line
                for(  ; i1 < strlen(bar); i1++){

                    char c = bar[i1]; 
                    printf("\ncharacter : %c, position :%d",c,i1);

                    if(c=='|'){ 
                        pass++;
                        printf("\nchar is |, pass is :%d, ",pass);

                        if(pass == 1){
                            if(g1 == 1){ barpos = i1; printf("g1 open, barpos is %d \n",barpos); i1++; break; }

                        }else if(pass == 2){
                            if(g2 == 1){ barpos = i1; printf("g2 open, barpos is %d \n",barpos); i1++; break; }

                        }else if(pass == 3){ 
                            if(g3 == 1){ barpos = i1; printf("g3 open, barpos is %d \n",barpos); i1++; break; }
                        }

                    }
                }                

                if(i==0){ position1 = barpos; } else { position2 = barpos; }
                printf("\n\nposition1 is: %d, position2 is: %d", position1,position2);
            }


            int stringsize = (position2 - position1)-2; // x|abvvcd| : 0 1 (2 3 4 5 6 7) 8

            char cmp_str[stringsize+1];
            cmp_str[0] = '\0';

            int counter_start = position1+1;
            int cmp_counter = 0;
            for(int i = counter_start; i < position2; i++){
                cmp_str[cmp_counter] = bar[i];
                cmp_counter++;
            }

            cmp_str[stringsize+1] = '\0';


            lineNo++;
            //compare copied string with function argument
            if(strcmp(cmp_str,value)==0){
                printf("\n found match!");
                returnint = lineNo;
                break;
            }else{ printf("\ndid not match...");}

            memset(readbuffer,'\0',sizeof(readbuffer)); //reset line buffer?

        }

        if(returnint < 1){ returnint = -1;  }
        fclose(file);

    }else{ 
        printf("\ntxt file does not exist"); returnint = -3; 
        return returnint;  
    }


    printf("\n- leaving searchRecord function -");
    return returnint;
}




/* CHECKFILE function
(check if data directory and records_file txt file exist)
function returns 0 - file does not exist, 1 - file exists, 
-1 - function fail */
int checkFile(){
    printf("\n- starting records checkFile function -\n");
    int exists = 0;

    DIR* dirStream = opendir("data");
    if(dirStream){
        printf("\ndirectory exists");

        if(access("./data/records_file.txt",F_OK) != -1){
            printf("\nfile exists!");
            exists = 1;
        }else { printf("\nfile does not exist"); }

        closedir(dirStream); //close directory stream

    }else if(ENOENT == errno){
        printf("\ndirectory does not exist");

    }else{  printf("\nopendir failed (other reason)"); exists = -1; }

    printf("\n- leaving records checkFile function -\n");
    return exists;
}



int main(){
    //addRecord("   test fo  ","  53,sams st  ","   222 222 222");
    int result = searchRecord(1,"test 2");
    printf("\nresult is: %d\n",result);

}

1 个答案:

答案 0 :(得分:0)

根据建议纠正的功能。这段代码似乎给出了正确的结果。不知道是否存在目前看不见或出现的故障。

第一位纠正码:

printf("\n--------LINE %d-------\n",lineNo);

    //get string segment from column
    char bar[strlen(readbuffer)+2]; //string with | added to start   <=====+1 for \0  bar has no terminator
    bar[0] = '|';
    strcpy(bar+1,readbuffer);
    strcat(bar,"\0");       

第二次调整(以前是(pos2-pos1)-2):

int stringsize = (position2 - position1)-1; 
// x|abvvcd|    : 0 1 (2 3 4 5 6 7) 8
// aaff|ccw|wff     : 0 1 2 3 4 5 (6 7 8) 9 10 11 12 
// qqe|essaaf|f : 0 1 2 3 4 (5 6 7 8 9 10) 11 12 

整个函数(现在显示将字符复制到数组中):

//assumes looking for exact match
//check column 1 or 2
int searchRecord(int column,char* value){
    printf("\n- starting searchRecord function -");
    int returnint = 0; //value to return


    //gates used for getting bar positions
    int g1 =0; //bar 1
    int g2 =0; //bar 2
    int g3 =0; //bar 3

    if(column == 1){
        g1 = 1;
        g2 = 1;
    }else if(column == 2){
        g2 = 1;
        g3 = 1;
    }

    printf("\ngates are: g1:%d g2:%d g3:%d",g1,g2,g3);



    int lineNo = 0; //track line number in file

    int txtexists = checkFile(); //check "records_file.txt" file exists using opendir and access functions
    if(txtexists==1){

        FILE* file = fopen("./data/records_file.txt","r");
        if(file==NULL){ printf("\nfopen error"); returnint = -3; return returnint; }        


        char readbuffer[250] = "";


        while(fgets(readbuffer,250,file)){ //loop through file lines

            printf("\n--------LINE %d-------\n",lineNo);

            //get string segment from column
            char bar[strlen(readbuffer)+2]; //string with | added to start   <=====+1 for \0  bar has no terminator
            bar[0] = '|';
            strcpy(bar+1,readbuffer);
            strcat(bar,"\0");           

            printf("\nstring line read from file is - %s", bar);


            int position1 = 0; //first bar index
            int position2 = 0; //second bar index

            int barpos = -1; 
            int pass = 0;
            int i1 = 0; //char index counter

            //loop for position1 and position2 of bars
            for(int i = 0; i < 2; i++){
                printf("\ngetting | %d position",i+1);

                printf("\ni1 cycle(%d) : %d",i,i1);

                //loop through characters of (bar)line
                for(  ; i1 < strlen(bar); i1++){

                    char c = bar[i1]; 
                    printf("\ncharacter : %c, position :%d",c,i1);

                    if(c=='|'){ 
                        pass++;
                        printf("\nchar is |, pass is :%d, ",pass);

                        if(pass == 1){
                            if(g1 == 1){ barpos = i1; printf("g1 open, barpos is %d \n",barpos); i1++; break; }

                        }else if(pass == 2){
                            if(g2 == 1){ barpos = i1; printf("g2 open, barpos is %d \n",barpos); i1++; break; }

                        }else if(pass == 3){ 
                            if(g3 == 1){ barpos = i1; printf("g3 open, barpos is %d \n",barpos); i1++; break; }
                        }

                    }
                }                

                if(i==0){ position1 = barpos; } else { position2 = barpos; }
                printf("\n\nposition1 is: %d, position2 is: %d", position1,position2);
            }


            int stringsize = (position2 - position1)-1; 
            // x|abvvcd|    : 0 1 (2 3 4 5 6 7) 8
            // aaff|ccw|wff     : 0 1 2 3 4 5 (6 7 8) 9 10 11 12 
            // qqe|essaaf|f : 0 1 2 3 4 (5 6 7 8 9 10) 11 12 


            char cmp_str[stringsize+1];
            cmp_str[0] = '\0';

            int counter_start = position1+1;
            int cmp_counter = 0;

            printf("\nstring size is: %d",stringsize);
            printf("\ncom_str size is: %d",stringsize+1);
            printf("\ncounter start position is %d",counter_start);
            printf("\ncompare counter is: %d",cmp_counter);

            for(int i = counter_start; i < position2; i++){
                cmp_str[cmp_counter] = bar[i];

                printf("\nbar[%d]-(%c) goes to cmp_str[%d]",i,bar[i],cmp_counter);

                cmp_counter++;
            }

            cmp_str[stringsize+1] = '\0';


            lineNo++;
            //compare copied string with function argument
            if(strcmp(cmp_str,value)==0){
                printf("\n found match!");
                returnint = lineNo;
                break;
            }else{ printf("\ndid not match...");}

            memset(readbuffer,'\0',sizeof(readbuffer)); //reset line buffer?

        }

        if(returnint < 1){ returnint = -1;  }
        fclose(file);

    }else{ 
        printf("\ntxt file does not exist"); returnint = -3; 
        return returnint;  
    }


    printf("\n- leaving searchRecord function -");
    return returnint;
}