本文介绍了使用fgets()在C / C ++中读取comport的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来通过comport发送命令并接收响应。目前我可以打开/关闭并写入comport,但无法让fgets()从comport中读取一行。目前程序在将字符串发送到comport后崩溃。我正在使用windows(visual studio 2008)。



以下代码



谢谢





  #include     stdafx.h 
#include < string.h >
#include < conio.h >
#include < stdlib.h >

int m ain( void

{
char str [ 80 ];
char rstr [ 80 ];
char buff [ 256 ];

FILE * comport;
if ((comport = fopen( COM1 wt))== NULL)
{
printf( 无法打开通讯端口COM1 \ n);
printf( 端口可能被禁用或正在使用\ n);
printf( 输入\quit \退出\ n) ;
getch();
}
else
{
printf( COM1已成功打开\ n);

for (;;)
{
printf( 输入字符串\\\
);
fgets(str, 80 ,stdin);
printf( \ n%s \ n,str);
fprintf(comport, %s \ n,str);
fflush(comport);

fgets(buff, sizeof buff,comport);

strcpy(rstr,buff);
printf( s%\ n,rstr);

}
fclose(comport);


}
return 0 ;
}
解决方案



I'm trying write a program to send commands over the comport and receive a response. At the moment I can open/close and write to the comport but can't get fgets() to work reading a line in from the comport. At the moment the program crashes after sending the string to the comport. I am using windows (visual studio 2008).

code below

Thanks


#include "stdafx.h"
#include <string.h>
#include <conio.h>
#include <stdlib.h>

int main (void)

{
	char str[80];
	char rstr[80];
	char buff[256];

	FILE *comport;
	if ((comport = fopen("COM1", "wt")) == NULL)
		{
			printf("Failed to open the communication port COM1\n");
			printf("The port may be disabled or in use\n");
			printf("enter \"quit\" to exit \n");
			getch();
		}
	else
		{
		printf("COM1 opended successfully\n");

			for(;;)
			{
				printf ("enter a string \n");
				fgets (str , 80 , stdin);
				printf ("\n%s\n",str);
				fprintf (comport, "%s\n",str);
				fflush(comport);

				fgets(buff, sizeof buff, comport);

				strcpy(rstr, buff );
				printf("s%\n",rstr);

			}
		fclose(comport);


		}
	return 0;
}
解决方案



这篇关于使用fgets()在C / C ++中读取comport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 00:43