【问题标题】:Not able to read data in from a text file.无法从文本文件中读取数据。
【发布时间】:2016-03-07 19:12:01
【问题描述】:

我在查找要读取的文本文件的存储位置时遇到问题。我将它存储在与可执行文件相同的目录中,但它仍然没有读取文件。经过大量挖掘和搜索,我发现问题与 Xcode 中的“派生数据”有关。当我查找源文件时,通过右键单击 main.c 文件并在 finder 中找到该文件,我发现它位于派生数据中。每当我运行这个程序时,它都会创建一些派生数据(Xcode 应该这样做)但是我的 .c 文件存储在这个派生数据中,当我尝试将文本文件存储在可执行文件所在的同一位置时(同一位置.c 文件位于)我无法读取该文件。

建议?

想法?

帮助..

#include <stdio.h>
    #include <unistd.h>
    extern int errno;
    int main (void){
        int term;
        long long StudentID;
        char lastname [16];
        char firstname[16];
        char subject[4];
        int catalog;
        char  section[4];
        char  filename [9];
        FILE *cfPtr;
        printf("Enter file name: ");
        scanf("%s",filename);
        /*
         char cwd [1024];
         if (getcwd(cwd, sizeof(cwd)) != NULL)
         fprintf(stdout, "Current working dir: %s\n", cwd);
         */
        system("pwd");
        if((cfPtr=fopen(filename,"r"))==0){
            //printf("%s jlk",strerror(errno));
            printf("File could not be opened\n");
        }
        else{
            printf("%-35s%-10s%-10s%-10s%-10s\n","Last Name, First Name","Term","ID","Course","Section");
            int i;
            for(i=0; i<75; i++){
                printf("-");
            }
            fscanf(cfPtr,"%d%lld%s%s%s%d%s",&term,&StudentID,lastname,firstname,subject,&catalog,section);
            while(!feof(cfPtr)){
                printf("%-35s%-10s%d%lld%-10s%-10s\n", lastname, firstname,term,StudentID,subject,section);
                fscanf(cfPtr,"%d%lld%s%s%s%d%s",&term,&StudentID,lastname,firstname,subject,&catalog,section);
            }

            fclose(cfPtr);

        }
        return 0;
    }

【问题讨论】:

  • 离题:应该是while(fscanf(...)==7) 以避免while(!feof(...)) 并避免重复fscanf

标签: c xcode io text-files scanf


【解决方案1】:

如果您在 Xcode 中设置了“命令行工具”项目,则可以如下设置工作目录。首先点击Xcode窗口顶部的项目名称,选择“Edit Scheme...”

然后选择左侧的“Run Debug”并更改右侧的“Working Directory”。

另一种方法是下载命令行工具(首选项/下载)。然后你可以打开一个终端窗口,从命令行编译/运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多