您的位置:首页 > 编程语言 > C语言/C++

code block与VC++下相对路径的不同写法

2014-01-18 13:22 387 查看
最近想不借用超级宝典第五版的封装类自己完整写一个着色器,但是一直读取shader文件失败,原因在于相对路径的写法错误。

codeblock 下如下写即可读取

#include <stdio.h>
#include <stdlib.h>

char *ReadText(char *fn);

int main()
{
char *ff;
ff=ReadText("first.vert");
printf("%s\n",ff);
return 0;
}

char *ReadText(char *fn)
{
FILE *fp;
char *content = NULL;

int count=0;

if (fn != NULL)
{
fp = fopen(fn,"rt");

if (fp != NULL)
{

fseek(fp, 0, SEEK_END);  // 重定位流(数据流/文件)上的文件内部位置指针
// int fseek(FILE *stream, long offset, int fromwhere);
count = ftell(fp);       // long ftell(FILE *stream); 返回当前文件指针,是int类型
rewind(fp);  // void rewind(FILE *stream); 将文件内部的位置指针重新指向一个流(数据流/文件)的开头

if (count > 0)
{
content = (char *)malloc(sizeof(char) * (count+1));  // extern void *malloc(unsigned int num_bytes);
count = fread(content,sizeof(char),count,fp);  // 从一个流中读数据   
//函数原型: size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); 
// 				    buffer
// 					Storage location for data.
//
// 					size
// 					Item size in bytes.
//
// 					count
// 					Maximum number of items to be read.
//
// 					stream
// 					Pointer to FILE structure.

content[count] = '\0';
}
fclose(fp);
}
}
return content;

}


当前目录的写法为。

ff=ReadText("first.vert");


VC++2008则不同。

当前目录的写法为

ff=ReadText("../first.vert");


源代码如下:

#include <stdio.h>
#include <stdlib.h>

char *ReadText(char *fn);

int main()
{
char *ff;
ff=ReadText("../first.vert");
printf("%s\n",ff);
getchar();
return 0;
}

char *ReadText(char *fn)
{
FILE *fp;
char *content = NULL;

int count=0;

if (fn != NULL)
{
fp = fopen(fn,"rt");

if (fp != NULL)
{

fseek(fp, 0, SEEK_END);  // 重定位流(数据流/文件)上的文件内部位置指针
// int fseek(FILE *stream, long offset, int fromwhere);
count = ftell(fp);       // long ftell(FILE *stream); 返回当前文件指针,是int类型
rewind(fp);  // void rewind(FILE *stream); 将文件内部的位置指针重新指向一个流(数据流/文件)的开头

if (count > 0)
{
content = (char *)malloc(sizeof(char) * (count+1));  // extern void *malloc(unsigned int num_bytes);
count = fread(content,sizeof(char),count,fp);  // 从一个流中读数据   
//函数原型: size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); 
// 				    buffer
// 					Storage location for data.
//
// 					size
// 					Item size in bytes.
//
// 					count
// 					Maximum number of items to be read.
//
// 					stream
// 					Pointer to FILE structure.

content[count] = '\0';
}
fclose(fp);
}
}
return content;

}


如果访问上层文件则一次后退即可。

../name1/*.txt


更进一步请看如下两篇帖子:

http://blog.csdn.net/sszgg2006/article/details/8447176 http://bbs.csdn.net/topics/80326375[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: