【发布时间】:2019-04-05 05:57:14
【问题描述】:
我必须读取如下所示的 .txt 文件:
纽约,4:20,3:03 堪萨斯城,12:03,3:00 北湾,16:00,0:20 卡普斯卡辛,10:00,4:02 雷湾,0:32,0:31我试图将每个元素分成自己的数组是最终目标,因此我可以将其用于其他用途。
我的 while 循环正确读取文件,但仅将文件的最后一行存储在数组中,我无法找出原因。正在读取的文件也可以是任意数量的行。我确信它会读取每一行,因为它会打印出完美读取的每一行。所以我认为问题在于存储它正在阅读的内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996)
// a function to remove the trailing carriage return
void clearTrailingCarraigeReturn(char *buffer);
/* == FUNCTION PROTOTYPES == */
/* == CONSTANTS == */
#define RECORD_SIZE 256
#define NUM_RECORDS 5
#define CHUNK_SIZE 1024
#define STRING_SIZE 80
// MAIN
int main(int argc, char *argv[]) {
FILE *fp;
char flightInfo[RECORD_SIZE] = { 0 };
char cityName[20] = {};
char flightHour[20] = {};
char flightMin[20] = {};
char layoverHour[20] = {};
char layoverMin[20] = {};
int i = 0;
struct flightInfo {
char flightName[20];
double flightTime;
double layoverTime;
};
fp = fopen(argv[1], "r");
// first - we'll check the command-line arguments to ensure that the user specified
// a single argument - which we will assume is the name of a file
if (argc != 2) {
printf("Sorry - you need to specify the name of a file on the command line.\n");
return -1;
}
if (fp == NULL) {
printf("Can't open the TEXT file for reading\n");
return -4;
}
// get each of the lines from the file
while (fgets(flightInfo, sizeof flightInfo, fp) > 0) {
clearTrailingCarraigeReturn(flightInfo);
// display the line we got from the file
printf(" >>> read record [%s]\n", flightInfo);
}
// we exited the reading loop - was it because we read the EOF?
if (feof(fp)) {
printf(" [DONE reading the file ... we've reached the EOF]\n");
} else {
// we exited the loop because of an error
if (ferror(fp)) {
// there's an error
printf("Error reading a record from the file\n");
if (fclose(fp) != 0) {
// we can't even close the file
printf("Can't close the TEXT file we opened for reading\n");
}
return -5;
}
}
}
// This function locates any carriage return that exists in a record
// and removes it ...
void clearTrailingCarraigeReturn(char *buffer) {
char *whereCR = strchr(buffer, '\n');
if (whereCR != NULL) {
*whereCR = '\0';
}
}
【问题讨论】: