C任意サイズファイル(txt含む)を読み込んでcharとして出力

1316 ワード

char* Load_File_JSON(const char* filename)
{
	FILE *fp; char *str ; long flength;

	fp = fopen(filename, "r");
	if (!fp)
	{
		printf("!!FILE open ERROR 
"); return NULL; } fseek(fp,0,SEEK_END); flength = ftell(fp); fseek(fp,0,SEEK_SET); str = (char*)malloc(flength*sizeof(char)); assert(str!=NULL); fread(str,flength , 1, fp); printf("%s
",str); fclose(fp); return str; }
char* Load_File_AtLength(const char* filename,unsigned int ExLength,unsigned int *ReturnLength)
{
    FILE *fp; char *str ; long flength;

    fp = fopen(filename, "r");
    if (!fp)
    {
        printf("!!FILE open ERROR n");
        return NULL;
    }

    fseek(fp,0,SEEK_END);
    flength = ftell(fp);
    fseek(fp,0,SEEK_SET);

    if(flength>(long)ExLength)
    {
        str = (char*)malloc(ExLength*sizeof(char));
        assert(str!=NULL);
        fread(str,ExLength , 1, fp);
        *ReturnLength = ExLength ;
    }
    else{
        str = (char*)malloc(flength*sizeof(char));
        assert(str!=NULL);
        fread(str,flength , 1, fp);
        *ReturnLength = flength ;
    }

    printf("%s
",str); fclose(fp); return str; }

注意:サイズはlongを超えてはいけません.もちろん普通はできません.