
如何用C++访问某个目录下的文件
向各位高手求用c++在某个文件夹中建立文件,并对其进行读写操作的实现方法如:1.创建文件并写入字串的方法:voidfuntion(stringpath,stringstr...
向各位高手求用c++在某个文件夹中建立文件,并对其进行读写操作的实现方法
如:
1.创建文件并写入字串的方法:
void funtion(string path,string str)
参数为某文件的路径,和输出的内容
2.读取某文件夹下的文件的方法;
string funtion(string path)
参数为某文件的路径,返回文件内容的字串
越详细越好~~
谢谢o:-);
额~~~~那怎样在某个指定的路径建立文件夹?
fstream可以指定文件路径吗?如何做?
createfile和readfile具体怎样用吖?需要include什么头文件?
查过msdn但是看不懂额~~大大给个例子吧~谢谢了 展开
如:
1.创建文件并写入字串的方法:
void funtion(string path,string str)
参数为某文件的路径,和输出的内容
2.读取某文件夹下的文件的方法;
string funtion(string path)
参数为某文件的路径,返回文件内容的字串
越详细越好~~
谢谢o:-);
额~~~~那怎样在某个指定的路径建立文件夹?
fstream可以指定文件路径吗?如何做?
createfile和readfile具体怎样用吖?需要include什么头文件?
查过msdn但是看不懂额~~大大给个例子吧~谢谢了 展开
3个回答
展开全部
变量用char 型, 不是用 string 类(class).
文件名传入的简单办法是通过位置参数:
void main (int argc, char *argv[]){
char my_path[80],my_name[32], filename[120];
if (argc < 3){
printf("Uasge:%s path_string file_name\n",argv[0]);
exit(0);
}
strcpy(my_path,argv[1]); // 路径名
strcpy(my_name,argv[2]); // 文件名
sprintf(file_name,"%s\\%s",my_path,my_name);
// 全名 在 file_name 里
}
运行时打入:
程序名 路径名 文件名
例如:
myprog "C:\\program files\\src" abc.txt
路径名用引号是因为路径含空白,若不含空白,可以不要引号.
文件名传入的简单办法是通过位置参数:
void main (int argc, char *argv[]){
char my_path[80],my_name[32], filename[120];
if (argc < 3){
printf("Uasge:%s path_string file_name\n",argv[0]);
exit(0);
}
strcpy(my_path,argv[1]); // 路径名
strcpy(my_name,argv[2]); // 文件名
sprintf(file_name,"%s\\%s",my_path,my_name);
// 全名 在 file_name 里
}
运行时打入:
程序名 路径名 文件名
例如:
myprog "C:\\program files\\src" abc.txt
路径名用引号是因为路径含空白,若不含空白,可以不要引号.
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
readfile就得了呗
先createfile得到文件的句柄,然后调readfile
先createfile得到文件的句柄,然后调readfile
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
楼上说得没错,string是在类(class)中用的.而这里用的是函数!所以改为char* str;下面写个设置 path="D:\\1.txt";
字符串:char* str="hello world";
当然,你也可以自己读入字符串!
代码如下:
# include <stdio.h>
# include <iostream.h>
# include<string.h>
//函数funwrite:写入文件!
void funwrite(char* path,char* str)
{
FILE *f;
f=fopen(path,"wb");
fwrite(str,strlen(str),1,f);
fclose(f);
}
//函数funread:读取文件!
void funread(char* path)
{
FILE *f;
char ch;
f=fopen(path,"r");
while(!feof(f))
{
ch=fgetc(f) ;
if(ch!='\n')
{
// printf("%c",ch);
cout<<ch;
}
}
cout<<endl;
// printf("\n");
fclose(f);
}
void main()
{
char* path="D:\\1.txt"; //设置文件路径
char* str="hello world"; //设置字符串
funwrite(path,str);
funread(path);
}
字符串:char* str="hello world";
当然,你也可以自己读入字符串!
代码如下:
# include <stdio.h>
# include <iostream.h>
# include<string.h>
//函数funwrite:写入文件!
void funwrite(char* path,char* str)
{
FILE *f;
f=fopen(path,"wb");
fwrite(str,strlen(str),1,f);
fclose(f);
}
//函数funread:读取文件!
void funread(char* path)
{
FILE *f;
char ch;
f=fopen(path,"r");
while(!feof(f))
{
ch=fgetc(f) ;
if(ch!='\n')
{
// printf("%c",ch);
cout<<ch;
}
}
cout<<endl;
// printf("\n");
fclose(f);
}
void main()
{
char* path="D:\\1.txt"; //设置文件路径
char* str="hello world"; //设置字符串
funwrite(path,str);
funread(path);
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询