【问题标题】:My C program reads a text file. When I put it into Xcode it fails. What's happening?我的 C 程序读取一个文本文件。当我将它放入 Xcode 时,它​​失败了。发生了什么?
【发布时间】:2014-11-10 17:25:46
【问题描述】:

我有一个打开 .txt 的函数,使用 fscanf 读取格式如下的数字:

532
2
-234
32

等等。当我使用 GCC 编译时它成功地做到了这一点,但是我无法在 Xcode 中打开文件,为什么? 相关代码为:

int main (void){
    FILE *infile = NULL;  //input file buffer
    int int_array[100];   //an integer array 100 entries long
    char infilename[256];  //an extra large char array 
        //this entire while loop was provided as part of the assignment, 
        //we weren't supposed to change it. I've finished this assignment, 
        //but now I want to know how to use my Xcode debugger
    while(infile == NULL) {
        printf("Input filename:");     //user prompt
        scanf("%s",infilename);        //store user input in large char array
        if((infile = fopen(infilename, "r")) == NULL) {      //input file buffer opens file
            printf("ERROR: file %s can not be opened!\n",in filename); //error if can not open
        }
    }
    int arraySize =0;

    while (!feof(readfile)) {           //StackOverflow showed me how to use this function.
        fscanf(readfile, "%d", (array+arraySize));
        arraySize++;
    }
    //more code...
}

在我的 Xcode 项目中,我将 hw1.c、hw1_functions.c、input.txt 和一些未调用的 c 函数都放在同一个文件夹中。当我运行程序时,它会提示我输入文件名。我说 input.txt 就像我在使用 GCC 后在终端中一样,但我得到“错误文件 input.txt 无法打开!” 我需要做些什么来完成这项工作吗?

【问题讨论】:

  • 也许验证您当前的工作目录?
  • 我在下面的回答有帮助吗?
  • @XavierDass 是的!年轻的笨蛋我不太擅长SO。我的道歉。

标签: c xcode fopen


【解决方案1】:

确保 input.txt 文件不在项目文件夹中,而是在与编译程序相同的文件夹中。您可以通过右键选择 Xcode 左侧窗格中“产品”文件夹下的可执行文件并选择“在查找器中显示”然后将 .txt 文件移动到那里并再次运行来找到它。

【讨论】:

    【解决方案2】:

    我今天也遇到了同样的问题。我想将 C 代码添加到我的 Swift 项目中,而我的文件指针始终为 NULL。

    不幸的是,在 XCode 9 for iOS 应用程序中,我无法更改工作目录。更改构建阶段也对我没有帮助。经过 4 个多小时的反复试验,这就是我最终想出的方法,并且可以正常工作:

    1. 在将文件复制到 XCode 时,我选择了“创建组”,但我需要选择“创建文件夹引用”:

    1. 我创建了一个新的 Objective-c 文件 (.m) 并将我的所有 C 代码复制到那里。

    2. 我没有修改 .h 文件(XCode 生成的桥接头和我自己的带有公共函数声明的 .h 文件)。现在我的项目结构如下所示:

    1. 在我的 dict.m 文件中代替之前的纯 c fopen 部分:

      FILE *dic = fopen("dictionary.txt", "r");
      

      我添加了 obj-C 代码:

      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dictionary" ofType:@"txt"];
      FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
      

    它现在可以正常工作了!真是太棒了!

    ps 我决定写下这个答案,以防它对像我这样的人有所帮助并节省他们一些时间。如果您知道如何在 XCode 9 for iOS 中更改工作目录,请给我留言 - 现在我真的很好奇为什么我找不到它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2015-03-26
      • 2021-06-20
      • 2021-10-01
      • 2011-06-19
      • 2011-01-11
      相关资源
      最近更新 更多