1.声明变量尽量在函数开头

#include <stdio.h>
#include <string.h>
char name[]=”mygogou”;
int main()
{
    char output[8];
    strcpy(output, name);
    for(int i=0;i<8&&name[i];i++)
    printf(“\\0x%x”,name[i]);
    return 0;
}

写在.c文件中会编译报错。

Compiling…
tmsg.c
E:\as\vc-code\1\tmsg.c(8) : error C2143: syntax error : missing ‘;’ before ‘type’

经查证这是因为c和c++关于变量声明的一点点不同:

C语言是要求你必须将变量在函数开始处进行声明的,不支持在任意地方声明变量。

因此换成这样的就编译通过啦:

#include <stdio.h>
#include <string.h>
char name[]=”mygogou”;
int main()
{
    char output[8];
    int i;
    strcpy(output, name);
    for(i=0;i<8&&name[i];i++)
    printf(“\\0x%x”,name[i]);
    return 0;
}

在C++语言中无这种限制。但是个人倾向于将声明放在函数开头部分,参加3GLive期间的问题。

2.fwrite和fprintf存在缓冲区

是先写到内存的,fprintf,fwrite都是从用户缓冲写到标准io的缓冲,然后从标准io的缓冲到内核缓冲,最后才由操作系统写入文件。

  1. 文件缓冲区滿时自动写入文件
  2. 强制文件缓冲区时自动写入文件:如fflush(),fclose()及程序结束等

因而一定记得fflsuh()和fclose()否则,当程序没有正常返回,Ctrl-C或者crash时,buffer就被drop鸟。

int main()
{
	FILE *fpRead, *fpWrite;
	if((fpRead = fopen("d:\\test.txt", "r")) != NULL)
    {
		if(remove("d:\\test.txt")==-1)
		{
			printf("could not delete.");
		}
    }
	fpWrite=fopen("d:\\test.txt", "at+");
	char x[11]="FUCK YOU2!";
	//fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fpWrite);
	for(int i=0; i<11; i++)
	{
		fprintf(fpWrite, "%c", x[i]);
	}
	fprintf(fpWrite, "\n");
	fprintf(fpWrite, "hello");
	fflush(fpWrite);
	return 0;
}