我在目录中创建了一个名为 mahmoud.txt 的文件:/Users/mahmoudhamra/Desktop/C language/
我想在 Xcode 中打开它。
我将目录和文件名分别创建为一个字符串。 然后我将文件名连接到目录并尝试打开它来读取它,但它总是给我一个错误:“线程 1:信号 SIGBART”。
有人可以帮我吗? 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[]) {
FILE *inFile;
char fileName[13];
printf("enter file name: ");
scanf("%s",fileName);
char new[40]="/Users/mahmoudhamra/Desktop/C language/";
strcat(new, fileName);
inFile=fopen("new", "r");
if (inFile== NULL) {
printf("file %s was not opened!\n", fileName);
printf("check that the file exists!\n");
exit(1);
}
else
printf("the files has successfully been opened!\n");
return 0;
}
最佳答案
首先
char new[40]="/Users/mahmoudhamra/Desktop/C language/";
至少应该是
char new[41]="/Users/mahmoudhamra/Desktop/C language/";
为空终止符留出空间。 C 字符串是一个字符数组,最后一个字符为空终止符(0x00
、'\0'
、0
)。
最好的是:
char new[]="/Users/mahmoudhamra/Desktop/C language/";
顺便说一句,你的问题是你没有空间添加 filename
字符,所以至少你应该将其定义为
char path_and_file[128] = {0};
strncpy(path_and_file, "/Users/mahmoudhamra/Desktop/C language/", sizeof(path_and_file)-1);
如果您想了解有关动态分配的知识,您可以:
char *directory = "/Users/mahmoudhamra/Desktop/C language/";
char *path_and_file = malloc(strlen(directory)+1);
if (path_and_file != NULL)
{
strcpy(path_and_file, directory);
printf("enter file name: ");
scanf("%s",fileName);
path_and_file = realloc(path_and_file,strlen(directory)+strlen(filename)+1);
if (path_and_file != NULL)
{
strcat(path_and_file, filename);
// YOUR STUFF
}
}
free(path_and_file);
动态分配的另一种方法是使用 strdup 创建第一个字符串:
char *path_and_file = strdup("/Users/mahmoudhamra/Desktop/C language/");
编辑
最后一件事,正如 @visibleman 指出的,对 fopen
的调用必须更改为
inFile=fopen(new, "r");
或者根据我的例子:
inFile=fopen(path_and_file, "r");
关于c - 如何用 C 语言打开 Xcode 中的现有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429451/