我的线路上似乎有一个语法错误
FSFILE *file; 在下面的代码中添加sprintf()行之后。代码一直在运行,直到我添加了char text、textresult和sprintf()。我似乎找不到它出了什么问题。我使用的是C18编译器。该代码用于使用SPI将数据写入SD卡。char txt[]是使用温度传感器测量得到的值,例如: 23,5。但我想在其中添加更多文本。目标是每隔5分钟在SD卡上存储一个测量值,以及一个时间戳或其他东西。我用的是PIC18f27j53。
void writeFile()
{
unsigned char txt[]={ftc(result,0),ftc(result,1),0x2C,ftc(result,3)};
unsigned char text[]= "hello";
unsigned char textresult[];
sprintf(textresult, "%c%c", txt, text);
//unsigned char size = sizeof(result)-1;
FSFILE *file;
file = FSfopenpgm("DATA.TXT", "w");
if(file == NULL)while(1);
if(FSfwrite((void *) txt, 1, 4, file)!=4)while(1);
if(FSfclose(file)!=0)while(1);
}发布于 2018-03-05 22:57:22
将sprintf(...)移到声明变量的位置之后。
发布于 2018-03-05 23:21:07
我不知道ftc是做什么的,但你的txt可能不是'\0'-terminated,如果你想把它用作字符串,它必须是'\0'-terminated。
而且你的textresult是一个空数组,如果你在没有可用空间的地方写东西,你期望会发生什么呢?
unsigned char textresult[20];都是正确的。
还要注意,printf中的%c只需要一个char值,您传递的是一个指向整个char序列的指针,这是未定义的行为。您必须使用%s (对于此txt,必须为'\0'-terminated),或者传递txt[0],即单个char
sprintf(textresult, "%c%c", txt[0], text);
// or
unsigned char txt[]={ftc(result,0),ftc(result,1),0x2C,ftc(result,3), 0};
...
sprintf(textresult, "%s%c", txt, text); 如果编译器希望在函数的开头声明所有变量,请将
FSFILE *file;在sprintf调用之前。
https://stackoverflow.com/questions/49113214
复制相似问题