c语言读取文件的路径怎么设定

c语言读取文件的路径怎么设定,第1张

//获取指定目录下的所有文件列表 author:wangchangshaui jlu

char** getFileNameArray(const char *path, int* fileCount)

{

int count = 0

char **fileNameList = NULL

struct dirent* ent = NULL

DIR *pDir

char dir[512]

struct stat statbuf

//打开目录

if ((pDir = opendir(path)) == NULL)

{

myLog("Cannot open directory:%s\n", path)

return NULL

}

//读取目录

while ((ent = readdir(pDir)) != NULL)

{ //统计当前文件夹下有多少文件(不包括文件夹)

//得到读取文件的绝对路径名

snprintf(dir, 512, "%s/%s", path, ent->d_name)

//得到文件信息

lstat(dir, &statbuf)

//判断是目录还是文件

if (!S_ISDIR(statbuf.st_mode))

{

count++

}

} //while

//关闭目录

closedir(pDir)

// myLog("共%d个文件\n", count)

//开辟字符指针数组,用于下一步的开辟容纳文件名字符串的空间

if ((fileNameList = (char**) myMalloc(sizeof(char*) * count)) == NULL)

{

myLog("Malloc heap failed!\n")

return NULL

}

//打开目录

if ((pDir = opendir(path)) == NULL)

{

myLog("Cannot open directory:%s\n", path)

return NULL

}

//读取目录

int i

for (i = 0(ent = readdir(pDir)) != NULL &&i <count)

{

if (strlen(ent->d_name) <= 0)

{

continue

}

//得到读取文件的绝对路径名

snprintf(dir, 512, "%s/%s", path, ent->d_name)

//得到文件信息

lstat(dir, &statbuf)

//判断是目录还是文件

if (!S_ISDIR(statbuf.st_mode))

{

if ((fileNameList[i] = (char*) myMalloc(strlen(ent->d_name) + 1))

== NULL)

{

myLog("Malloc heap failed!\n")

return NULL

}

memset(fileNameList[i], 0, strlen(ent->d_name) + 1)

strcpy(fileNameList[i], ent->d_name)

myLog("第%d个文件:%s\n", i, ent->d_name)

i++

}

} //for

//关闭目录

closedir(pDir)

*fileCount = count

return fileNameList

使用C语言的文件 *** 作函数可以读写txt文件,如果使用相对路径,文件必须放在程序相同的文件夹内。

1、C语言标准库提供了一系列文件 *** 作函数。文件 *** 作函数一般以f+单词的形式来命名(f是file的简写),其声明位于stdio.h头文件当中。例如:fopen、fclose函数用于文件打开与关闭;fscanf、fgets函数用于文件读取;fprintf、fputs函数用于文件写入;ftell、fseek函数用于文件 *** 作位置的获取与设置。

2、例程:

#include<stdio.h>

int a

char b,c[100]

int main(){

    FILE * fp1 = fopen("input.txt", "r")//打开输入文件

    FILE * fp2 = fopen("output.txt", "w")//打开输出文件

    if (fp1==NULL || fp2==NULL) {//若打开文件失败则退出

        puts("不能打开文件!")

        rturn 0

    }

    fscanf(fp1,"%d",&a)//从输入文件读取一个整数

    b=fgetc(fp1)//从输入文件读取一个字符

    fgets(c,100,fp1)//从输入文件读取一行字符串

    

    printf("%ld",ftell(fp1))//输出fp1指针当前位置相对于文件首的偏移字节数

    

    fputs(c,fp2)//向输出文件写入一行字符串

    fputc(b,fp2)//向输出文件写入一个字符

    fprintf(fp2,"%d",a)//向输出文件写入一个整数

    

    fclose(fp1)//关闭输入文件

    fclose(fp2)//关闭输出文件,相当于保存

    return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/8041485.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-12
下一篇 2023-04-12

发表评论

登录后才能评论

评论列表(0条)

保存