【发布时间】:2019-11-13 23:06:54
【问题描述】:
这段代码旨在读取两个文件的内容,并将它们存储到两个双字符指针中,以便每个数组的每个元素存储每个文件的一行。读取文件时,我告诉程序打印行,它会完全按照编写的方式打印。但是,当我尝试打印甚至整个数组本身的数组的随机元素时,在 foo 循环之外,程序返回 NULL 或不打印任何内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
//Opening the files
FILE * file_1 = fopen("file1.ll", "r");
FILE * file_2 = fopen("file2.ll", "r");
if (file_1 == NULL || file_2 == NULL) {
perror("Error opening file\n");
}
//Here I create a temporary string
char temp_string [1000];
// I create an array of strings
char ** string_1 = (char **)malloc (sizeof(char * ) * 1000);
int i = 0;
//size_1 and size_2 will be used to account for the effective size of the arrays
int size_1 = 0, size_2 = 0;
//I read the file into temp_string
while (fgets(temp_string, 1000, file_1) != NULL) {
string_1[i] = (char *) malloc (sizeof(char) * 1000);
//Then I copy temp_string to the element i of string_1
strcpy (string_1[i], temp_string);
//I print the string
fputs(string_1[i], stdout);
//and increase the size
size_1++;
}
printf("\n\n\n\n\n\n\n\n\n\n\n");
//I do the same for file 2
char temp_string_2 [1000];
char ** string_2 = (char **)malloc (sizeof(char * ) * 1000);
while (fgets(temp_string_2, 1000, file_2) != NULL) {
string_2[i] = (char *) malloc (sizeof(char) * 1000);
strcpy (string_2[i], temp_string_2);
fputs(string_2[i], stdout);
size_2++;
}
//Until now everything is okay. The compiler warns nothing and the code is read and printed.
//I've put big spaces to facilitate the reading of the code
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//Here I try to print the first four elements of string_1, but string_1[2] and
//string_1[3] return NULL
printf("%s%s%s%s\n\n", string_1[0], string_1[1],string_1[2],string_1[3]);
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//Here only two lines are printed
for (int i=0; i<size_1; i++) {
fputs(string_1[i], stdout);
}
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i=0; i<size_2; i++) {
fputs(string_2[i], stdout);
}
system("pause");
return 0;
}
【问题讨论】:
-
关于:
perror("Error opening file\n");这只会打印第二次调用fopen()的结果建议:FILE * file_1; if( !( file_1 = fopen( "file1.ll", "r" ) ) ) { perror( "fopen for file_1.ll failed" ); exit( EXIT_FAILURE );} and a similar logic forfopen()` of file_2.ll -
OT:关于:
char ** string_1 = (char **)malloc (sizeof(char * ) * 1000);1) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱。建议删除该演员表。 2) 始终检查 (!=NULL) 返回值以确保操作成功。如果不成功,请致电perror( "malloc failed" ); exit( EXIT_FAILURE ); -
OT:为了便于阅读和理解:1)请遵循公理:每个语句只有一个语句行和(最多)一个变量声明。
-
OT:关于:
char ** string_1 = malloc (sizeof(char * ) * 1000);更好用:calloc()而不是malloc(),那么无需计算使用了多少条目。循环直到遇到 NULL 条目 -
OT:关于:
while (fgets(temp_string, 1000, file_1) != NULL) {灵活,更好用:while (fgets(temp_string, sizeof( temp_string ), file_1) != NULL) {那么如果temp_string的长度改变了,代码中只需要修改一处