c - 如何用 C 语言打开 Xcode 中的现有文件?

标签 c xcode string data-files

我在目录中创建了一个名为 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/

相关文章:

c - MicroFocus cobol 命令 cobinit、cobcall 和 cobtidy 在我的 C 程序中抛出错误

ios - 为什么我在 Storyboard (Xcode) 中所做的更改没有反射(reflect)在我的应用程序上?

string - 如何在 Swift 中将 "Index"转换为类型 "Int"?

python - 在字符串 Python 中查找多个标记的字符串

c - 如何在以变量作为引用的函数内初始化结构

c - 为什么不能使用realloc函数来调整动态数组的堆栈大小?

ios - 授予 ViewController 访问数据和 Controller 类的权限

c - 这应该是 int,那我们为什么要使用 %s?

c++ - OpenMP #pragma omp for v/s #pragma omp parallel for之间的区别?

ios - 从uitableviewcell调用并使用uitableview?