我正在编写一个程序,使用文件符号和命令行语句从文件中获取输入,将输入填充到结构中,并将输入保存到另一个文件中。我也有一个排序功能,但我忽略了它,因为我认为它与我的问题无关。这是我第一次使用文件表示法,我无法将任何输出输入到我的输出文件中。关于为什么的任何想法?我已经尝试了一切,但无法让它工作。谢谢您的帮助。
/* structure declaration */
struct personCatalog {
char name[50];
char address[50];
char cityState[50];
char zipCode[7];
} ;
/* function prototypes */
void getPerson (struct personCatalog *arrayOfPointers[], int maxNumberOfPeople, FILE *inputFile);
void sortPerson (struct personCatalog *arrayOfPointers[]);
void putPerson(struct personCatalog *arrayOfPointers[], FILE *outputFile);
int main(int argc, const char * argv[]) {
int maxNumberOfPeople = 51;
struct personCatalog *pointerArray[maxNumberOfPeople];
/* add file streaming*/
FILE *inFile, *outFile;
inFile = fopen("/Users/myName/Desktop/inputText.txt", "r");
/* add command line statements */
if (( inFile = fopen(argv[1], "r")) == NULL) {
printf("Can't open the input file");
exit(1);
}
getPerson(pointerArray, maxNumberOfPeople, inFile);
sortPerson(pointerArray);
outFile = fopen("/Users/myName/Desktop/outputText.txt", "w");
if ((outFile = fopen(argv[2], "w")) == NULL) {
printf("Can't open the output file");
exit(1);
}
putPerson(pointerArray, outFile);
fclose(inFile);
fclose(outFile);
return 0;
}
/* function to fill the structures */
void getPerson (struct personCatalog *arrayOfPointers[], int maxNumberOfPeople, FILE *inputFile){
struct personCatalog *tempPointer;
int buffer = 512;
char stringCollector[buffer];
int num = 0;
while ((num < maxNumberOfPeople) && (fgets(stringCollector, buffer, inputFile) != NULL) ) {
/* dynamic memory allocation */
tempPointer = (struct personCatalog *) malloc(sizeof(struct personCatalog));
/* filling the structures */
strcpy(tempPointer->name, stringCollector);
fgets(tempPointer->address, buffer, inputFile);
fgets(tempPointer->cityState, buffer, inputFile);
fgets(tempPointer->zipCode, buffer, inputFile);
arrayOfPointers[num] = tempPointer;
num++;
}
/* adding a null character to the end of the pointer array */
arrayOfPointers[num] = '\0';
}
/* print function */
void putPerson(struct personCatalog *arrayOfPointers[], FILE *outputFile){
int num = 0;
while (arrayOfPointers[num] != NULL) {
printf("------Person #%d------\n", num);
fputs(arrayOfPointers[num]->name, outputFile);
fputs(arrayOfPointers[num]->address, outputFile);
fputs(arrayOfPointers[num]->cityState, outputFile);
fputs(arrayOfPointers[num]->zipCode, outputFile);
/* memory free */
free(arrayOfPointers[num]);
num++;
}
}