【问题标题】:Writing to file error写入文件错误
【发布时间】:2016-07-16 10:03:09
【问题描述】:

在我的代码中,我正在阅读一个名为 input-temps.txt 的文本文件(我下载了这个文件,并将它放在我正在处理的项目的文件夹中),其中包含每天要读取的 25 个温度值。我的程序读取这些值并将它们保存到一个数组中。计算完最大值、最小值和平均值后,它将这些值与每小时温度表一起写入我将调用的输出文件output-temps.txt

我的代码的问题是运行时找不到文件。我已经尝试过其他循环,但结果相同。我怎么了?

谢谢。

#include <stdio.h>
#include <stdlib.h>

//function prototype
void calc_results(int time[], int size);
void read_temps(int temp[]);

//set size of array as global value
#define SIZE 25

int main ()     {
    //Declare temperature array with size 25 since we are going from 0 to 24
    int i, temp[SIZE];

    read_temps(temp);
    //Temperature for the day of October 14, 2015
    printf("Temperature conditions on October 14, 2015:\n");
    printf("\nTime of day\tTemperature in degrees F\n\n");

    for (i = 0; i < SIZE; i++)
        printf( "%d \t\t%d\n",i,temp[i]);
    //call calc_results(temp, SIZE);
    calc_results(temp, SIZE);
    //pause the program output on console until user enters a key
    return 0;
}

/*The method read_temps that takes the input array temp
  and prompt user to enter the name of the input file
  "input.txt" and then reads the temperatures from the file
  for 24 hours of day */
void read_temps(int temp[])     {

    char fileName[50];
    int temperature;
    int counter=0;

    printf("Enter input file name : ");
    //prompt for file name
    scanf("%s",fileName);
    //open the input file
    FILE *fp=fopen(fileName, "r");
    //check if file exists or not
    if (fp=fopen("results.dat","r")== NULL)     {
        printf("File could not be opened.\n");
        //if not exit, close the program
        exit(0);
    }
    //read temperatures from the file input.txt until end of file is encountered
    while(fscanf(fp,"%d",&temperature)!=EOF)    {
        //store the values in the temp array
        temp[counter]=temperature;
        //increment the counter by one
        counter++;
    }
    //close the input file stream fp
    fclose(fp);
}

void calc_results(int temp[], int size)    {
    int i, min, max, sum = 0;
    float avg;
    min = temp[0];
    max = temp[0];
    //Loop that calculates min,max, sum of array
    for (i = 0; i < size; i++)    {
        if (temp[i] < min)    {
            min = temp[i];
        }
        if (temp[i] > max)    {
            max = temp[i];
        }
        sum = sum + temp[i];
    }
    avg = (float) sum / size;
    //open an external output file
    FILE *fout=fopen("output.txt","w");
    //Temperature for the day of October 14, 2015
    fprintf(fout,"Temperature conditions on October 14, 2015:\n");
    fprintf(fout,"\nTime of day\tTemperature in degrees F\n\n");
    //write time of day and temperature
    for (i = 0; i < SIZE; i++)    {
        fprintf( fout,"%d \t\t%d\n",i,temp[i]);
    }
    printf("\nMin Temperature for the day is : %d\n", min);
    printf("Max Temperature for the day is :%d\n", max);
    printf("Average Temperature for the day is : %f\n", avg);
    //write min ,max and avg to the file "output.txt"
    fprintf(fout,"\nMin Temperature for the day is : %d\n", min);
    fprintf(fout,"Max Temperature for the day is :%d\n", max);
    fprintf(fout,"Average Temperature for the day is : %f\n", avg);
    //close the output file stream
    fclose(fout);
}

【问题讨论】:

  • 找不到哪个文件?输入文件还是输出文件?
  • 我的第一个猜测是:您应该打印出您实际写入的目录。我的提示是:“./output.txt”和“output.txt”之间是有区别的。 :-)
  • this is the file 找不到哪个是输入
  • @MarkManning filename./filename 之间没有区别。
  • fp=fopen("results.dat","r")== NULL 1) 重写 fp。 2)需要( )(fp=fopen("results.dat","r"))== NULL

标签: c function loops


【解决方案1】:

要检查文件是否存在,您必须使用“access()”函数。首先包括:

#include <unistd.h>          // For "access()" function
#include <errno.h>           // For "errno"
#include <string.h>          // For "strerror()" function
// add your stuffs here ...
// .....
// .....
int status = access(filename, F_OK);
int saved_error = errno;              // For errno include <errno.h>
if (status == -1) {
    fprintf(stderr, "File Error: %s\n", strerror(saved_error));
    // For "strerror" include <string.h>
    exit(EXIT_FAILURE);
}
// Now here file will exist and can be opened as:
FILE *fptr = fopen(filename, "r");
saved_error = errno;    // Read more about errno: "man errno" commend in linux
// check for error 
if(fptr == NULL){
   fprintf(stderr, "File error: %s\n", strerror(saved_error);
   exit(EXIT_FAILURE);
}
// Now access you file using fptr...

【讨论】:

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