想要寫一個接收一個值之後,將這一個值寫檔到txt檔裡面
但是卻會出現txt檔的byte有問題,會寫檔有64byte又會清除規零,而且寫進去的內容也不是想要的字串,請問是記憶體的部分哪裡配置錯了嗎?
CSerial serial;
int main(){
if (serial.Open(3, 9600)){
printf("Port opened successfully");
char* lpBuffer = new char[50];
int nBytesRead = serial.ReadData(lpBuffer,50 );
while(1){
while (!nBytesRead)
{
FILE *fptr1;
fptr1 = fopen("C:\\Users\\User\\Desktop\\BlueTooth\\test.txt","w");
fprintf(fptr1,"%s",lpBuffer);
fclose(fptr1);
}
delete []lpBuffer;
}
}
else
{
printf("Failed to open port!");
}
system("pause");
return 0;
}
隨手改一改, 不一定能編譯也不一定能跑
#define BUFFER_SIZE 50
CSerial serial;
int main(){
if (serial.Open(3, 9600)){
printf("Port opened successfully");
char buffer[BUFFER_SIZE];
FILE *fptr1 = fopen("C:\\Users\\User\\Desktop\\BlueTooth\\test.txt","w");
while(1){
int nBytesRead = serial.ReadData(buffer, BUFFER_SIZE);
printf("received %d bytes", nBytesRead);
if (nBytesRead > 0) {
fwrite(buffer, sizeof(char), nBytesRead, fptr1);
} else {
printf("no data");
break;
}
}
fclose(fptr1);
} else {
printf("Failed to open port!");
}
system("pause");
return 0;
}
半夜的時候已經自己處理好了 謝謝你
if (serial.Open(3, 9600)){
printf("Port opened successfully\n");
char *lpBuffer =(char*)malloc(sizeof(char)*50);
FILE *fptr;
fptr = fopen("C:\\Users\\User\\Desktop\\BlueTooth\\test.txt","w");
while(1){
int dwBytesRead = serial.ReadData(lpBuffer,1 );
lpBuffer [1]= serial.ReadData(lpBuffer,0);
if(dwBytesRead){
fptr = fopen("C:\\Users\\User\\Desktop\\BlueTooth\\test.txt","w");
fprintf(fptr,"%s",lpBuffer);
printf("%s\n",lpBuffer);
fclose (fptr);
}