读取.txt文件和打印结果

时间:2017-11-18 18:54:39

标签: c arrays file io

我试图从单独的程序中读取我打印到.txt文件的信息,并将其显示在这个新程序中。虽然当我运行该程序时,它说该文件无法找到。我怀疑它是我的代码,而不是文件的位置,因为我已经仔细检查了我的硬代码,这是我到目前为止所做的,如果有人能指出我正确的方向那将是伟大的!

#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE      21

typedef struct data_slice
{
    int t;      // -> Time
    float tp;   // -> Valve pressure
    float tf;   // -> Sodium flow
    float tt;   // -> Sodium temp in Celsius
} data_slice;

void printIt(data_slice * data);

int main()
{
   float num;
   FILE *fptr;
   data_slice data[ARRAY_SIZE];

   if ((fptr =     fopen("/Users/captainrogers/Documents/output_data.txt","r")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   fscanf(fptr,"%f \n", &num);

    printIt(data);

   fclose(fptr);

   return 0;
}
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
    int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    // Print results to screen
    for (int i = 0, temp = indice; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[temp].t, data[temp].tp,     data[temp].tf, data[temp].tt);
        temp = (temp + 1) % ARRAY_SIZE;
    }

}

数据我试图从.txt打印:

-10  595.000000  15.000000   167.000000
 -9  557.000000  17.000000   168.000000
 -8  634.000000  17.000000   114.000000
 -7  656.000000  10.000000   183.000000
 -6  561.000000  13.000000   139.000000
 -5  634.000000  17.000000   124.000000
 -4  672.000000  19.000000   155.000000
 -3  527.000000  14.000000   166.000000
 -2  656.000000  11.000000   188.000000
 -1  661.000000  18.000000   141.000000
  0  689.000000  17.000000   146.000000
  1  624.000000  11.000000   104.000000
  2  504.000000  20.000000   120.000000
  3  673.000000  18.000000   147.000000
  4  511.000000  12.000000   114.000000
  5  606.000000  14.000000   171.000000
  6  601.000000  13.000000   159.000000
  7  602.000000  11.000000   127.000000
  8  684.000000  10.000000   194.000000
  9  632.000000  16.000000   139.000000
 10  651.000000  13.000000   168.000000

2 个答案:

答案 0 :(得分:0)

fopen("/Users/captainrogers/Documents/output_data.txt","r")

如果找不到该文件,请仔细检查您的路径。也许首先尝试使用包括驱动器号在内的完整路径。

fscanf(fptr,"%f \n", &num);

始终检查fscanf()的返回值。 "%f \n"可能不是您想要的格式字符串。

printIt(data);

主要问题:您从未将任何数据读入data[]

答案 1 :(得分:0)

fptr = fopen(“C://Users//captainrogers//Documents//output_data.txt”,“r”)) 如果您确定您的文档位于正确的文件中,请尝试使用此代码。

相关问题