我有一个名为test.txt的文本文件,其中包含以下文本:
文件路径/Desktop/file.txt
我需要在文件路径一词之后获取路径,并检查该文件在文件系统中是否实际存在。
我已使用strchr()和strtok()从文本文件中提取“ /Desktop/file.txt”,并将其与access()函数一起使用以检查是否存在。但是,它从未真正起作用,并说它即使实际上确实存在也不每次都存在。
这是我的代码的一部分,以尝试使其正常工作。
char *buffer = 0;
long length;
FILE *getfile;
getfile = fopen("test.txt", "r");
if (getfile){
fseek (getfile, 0, SEEK_END);
length = ftell (getfile);
fseek (getfile, 0, SEEK_SET);
buffer = malloc (length);
if (buffer){
fread (buffer, 1, length, getfile);
}
fclose (getfile);
}
char *getfilepath = (strchr(buffer, 'filepath') + 2);
int filepathexists = access(getfilepath, F_OK);
if(filepathexists == 0){
printf("The file exists.");
} else {
printf("File does NOT exist.");
}
这应该做。使用读取文件输入,fgets()
并使用来测试关键字strstr()
。我通常strtok()
将路径名与任何尾随newline
等隔离开来,但是由于路径可以包含空格,因此我一直谨慎地独立检查前导空格。注意:不要忘记free()
分配的内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(void)
{
int filepathexists = 0;
char *buffer, *sptr;
const char *cue = "filepath";
size_t length;
FILE *getfile;
getfile = fopen("test.txt", "r");
if (getfile){
fseek (getfile, 0, SEEK_END);
length = ftell (getfile); // find file size
fseek (getfile, 0, SEEK_SET);
buffer = malloc (length + 1); // allow for str terminator
if (buffer){
if (fgets(buffer, length + 1, getfile) != NULL) {
sptr = strstr(buffer, cue); // cue in correct place
if (sptr == buffer) {
sptr += strlen(cue); // skip past cue
while (*sptr == ' ') // and leading spaces
sptr++;
sptr = strtok(sptr, "\r\n\t"); // isolate path from newlines etc
if (sptr) {
printf("The file is: %s\n", sptr);
if (access(sptr, 0) != -1) {
filepathexists = 1;
}
}
}
}
free (buffer);
}
fclose (getfile);
}
if (filepathexists)
printf("The file exists.\n");
else
printf("File does NOT exist.\n");
return 0;
}
程序输出:
The file is: /Desktop/file.txt
The file exists.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句