目的:程序洗牌文本文件文件輸入到陣列由行字符串
的線讀取文件到一個數組
計數行和最大長度
計算陣列的最大寬度
獲取文件指針
這些是我想要在程序的第一部分中給你一些觀點。我不完全確定「獲取文件指針到底是什麼」。但是,我目前的問題是錯誤閱讀線作爲字符串數組。
已更新代碼seg。當我去打印混洗陣列時出現故障。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Accepts: command line input
// Returns: 0 if no error
int main(int argc, char *argv[]){
int x = 0, i, lineCount = 0, maxLen = 0;
char line[500], temp;
FILE *file = fopen(argv[1], "r");
// check if file exists
if (file == NULL){
printf("Cannot open file\n");
return 1;
}
// Gets lines, max length of string
while (fgets(line, sizeof(line), file) != NULL){
lineCount++;
if (strlen(line) > maxLen)
maxLen = strlen(line);
}
rewind(file);
char *lineArray[lineCount];
while (fgets(line, sizeof(line), file) != NULL) {
lineArray[x] = malloc(strlen(line));
if (lineArray[x] == NULL){
printf("A memory error occurred.\n");
return(1);
}
strcpy(lineArray[x], line);
// change \n to \0
lineArray[x][strlen(lineArray[x])-1] = '\0';
x++;
}
printf("File %s has %d lines with maximum length of %d characters\n",
argv[1], lineCount, maxLen);
printf("Original Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// Shuffle array
srand((unsigned int) time(NULL));
for (x = lineCount - 1; x >= 0; x--){
i = (int) rand() % lineCount;
temp = lineArray[x];
lineArray[x] = lineArray[i];
lineArray[i] = temp;
}
printf("\nShuffled Array\n");
for (x = 0; x < lineCount; x++)
printf("%2d %s\n", x, lineArray[x]);
// free allocated memory
for (x = 0; x < lineCount; x++)
free(lineArray[x]);
free(lineArray);
fclose(file);
return 0;
}
嘗試'fgets',而不是'fscanf'和'printf'內循環在循環結束之前將會出現segfault('lineArray [x] == NULL') – Kninnug