Por favor, avalie o meu código e me dar sugestões de como melhorar, por favor

Então, basicamente, eu tenho um código escrito para leitura da porta serial (arduino ligado no meu caso) e guardar isso para um arquivo de texto, e incrementar o arquivo de texto número por 1 a cada vez que o programa é executado.

Eu quero condensá-lo e livrar-se de qualquer noob erros de programação.

O código funciona bem, mas eu sei que não é tão elegante como poderia ser, e eu realmente quero melhorar. O seu conselho seria brilhante!

Eu já falei para os outros coordenadores e tinha básicas de ajudar, mas não muito.

int main(){
//OPENING SERIAL PORT

int res = 0;        //variables to be passed to functinos
int logNum = 0;
HANDLE hComm;
hComm = CreateFile( "\\\\.\\COM4",                //port name
                    GENERIC_READ | GENERIC_WRITE, //Read/Write
                    0,                            // No Sharing
                    NULL,                         // No Security
                    OPEN_EXISTING,// Open existing port only
                    0,            // Non Overlapped I/O
                    NULL);        // Null for Comm Devices

  if (hComm == INVALID_HANDLE_VALUE){ //print if COM port wont open
      printf("Error opening port");
      exit(42);
  }
  else {
      printf("Opening of port successful\n");   //Print to know serial port is open
  }

//Calling necessary functions
serialPort(hComm);
res = fileExist();
logNum = readPort(hComm, res);
parseFile(logNum);
CloseHandle(hComm);//Closing the Serial Port
return 0;   //main returns 0
}



void serialPort(HANDLE Comms){
//CONFIGURING SERIAL PORT
    BOOL Status;
    DCB dcbSerialParams = { 0 }; // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

    dcbSerialParams.BaudRate = CBR_57600;  // Setting BaudRate = 9600
    dcbSerialParams.ByteSize = 8;         // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;// Setting StopBits = 1
    dcbSerialParams.Parity   = NOPARITY;  // Setting Parity = None

    SetCommState(Comms, &dcbSerialParams); //Assignin serial settings to comm handle
    Status = EscapeCommFunction(Comms, SETRTS); //RTS Request to Send Signal to esentially reset Serial port (arduino)
    Status = EscapeCommFunction(Comms, SETDTR); //DTR data terminal ready, PC side terminal ready to recieve data

}


int fileExist(void){
//DOES FILENAME ALREADY EXIST

int result = 0;
char testNum[10];    
char fp[80];
char file[80] = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd[5] = ".txt";

for (int i = 1; i < 1000; i++){

    sprintf(testNum, "%%d", i); //converting testNum as int to string
    //adding test num to file dir
    strcpy(fp, file);       //adding strings to make file name
    strcat(fp, testNum);
    strcat(fp, fileEnd);
    printf("%%s", fp);

        /* Check for existence */
        if((_access(fp, 0 )) != -1 ){           //Function to check if file exists
            printf( "\nFile logs exists\n" );
        }
         else { //if file doesnt exists 
          printf("\nFile doesnt exist\n");
          result = i; //set result to equal current value for i
          break;
         }
    }
return result;  //send file num to next function
}


int readPort(HANDLE Comms, int testNum){
//READING DATA FROM SERIAL PORT
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
char word[14] = "Test Finished";  //Text to look for
char SerialBuffer[256];//Buffer for storing Rxed Data
DWORD NoBytesRead;  //set type for NoBytesRead
char Num[10];
sprintf(Num, "%%d", testNum);    //convert test num to string
char str[80];
//char buf[100];
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
//char tandd[8] = "_%%x_%%X";
char fileEnd[5] = ".txt";
//strftime(buf,64, "_%%x_%%X", timeinfo);
strcpy(str, file);      //adding strings to make file name
strcat(str, Num);
//strcat(str, buf);
strcat(str, fileEnd);
printf("%%s", str);

FILE *fp;    //create file pointer

fp = fopen(str, "w");   //create file to write serial data to

    do { //start do while loop
        ReadFile(Comms,           //Handle of the Serial port
                 SerialBuffer,       //
                 sizeof(SerialBuffer) -1,//Size of Buffer
                 &NoBytesRead,    //Number of bytes read
                 NULL);

        SerialBuffer[NoBytesRead] = '\0'; //Specify null terminator to stop data rxing strangly

        printf("%%s", SerialBuffer); //Print rx'd data to CMD
        fprintf(fp, "%%s", SerialBuffer); //Save rx'd data to txt file


        char *fin = strstr(SerialBuffer, word); //Find 'search' in SerialBuffer and assign to 'fin'

        //if fin has data then close Serial and close/save file
        if (fin != NULL){
            printf("Results Successfully logged \n \r \n \r");
            fclose(fp);         //close file
            fp = NULL;          //set file pointer to equal null to break from the loop
        }
    } while (fp != NULL);  //while, from do while loop
return testNum; //return testNum for use in another function
}



void parseFile(int fileNum){
//FUNCTION TO PARSE DATA FROM LOG FILE TO FIND FAILED TESTS

char Num[10];   //set Num as char and give extra memory
sprintf(Num, "%%d", fileNum); //Convert filenNum to string
char dir[80];   //set dir as char and give extra memory
char *file = "C:/Users/jgrayjt/Documents/Logs/TestLog_";
char fileEnd[5] = ".txt";
strcpy(dir, file);      //adding strings to make file name
strcat(dir, Num);
strcat(dir, fileEnd);
printf("%%s", dir);
FILE *fp1;      //create file pointer
char str[512];  //string to store data read from log file
const char fail[5] = "FAIL";    //text to look for
const char testnum[23] = "Test Iteration";     //text to look for
char *ret;  //create char variables
char *num;

fp1 = fopen(dir , "r");  //Open file to read

    if (fp1 == NULL){ //if you cant open file, print 
        printf("File open fail");
    }

    //Loop to find test number and fail strings  
    while( fgets (str, 512, fp1)!=NULL ) { 
        num = strstr(str, testnum); //find test num in string and assign to num
        ret = strstr(str, fail);    //find 'fail' in string and assign to ret

    if (ret != NULL && num != NULL){    //if both variables have data then print num
        printf("\n \r %%s\n\r", num);  //num has been given enough mem to include the fail that comes after it
    }
    }

fclose(fp1);    //close/save fil
getchar();
getchar();
}
-6
2019-09-19 11:41:56
origem
0 respostas

Veja mais perguntas por marcas