-2

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

2 回答 2

3

首先这

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");
于 2016-05-25T06:39:47.897 回答
1

问题几乎可以肯定是字符数组的大小,new因为它没有能力保存完整的文件名,并且会导致堆栈溢出:

char new[40]="/Users/mahmoudhamra/Desktop/C language/";
strcat(new, fileName);

更改401024

char new[1024] = ...;
于 2016-05-25T06:37:36.323 回答