我需要幫助來讀取 .txt 檔案的編號并將它們放入陣列中。但僅從第二行開始。我被困住了,不知道從我構建的代碼中去哪里。
.txt 檔案示例:
10 20
45000000
48000000
56000000
#define MAX 50
int main (void){
FILE *file;
int primNum;
int secNum;
int listOfNumers[50];
int numberOfLines = MAX;
int i = 0;
file = fopen("file.txt", "rt");
if (file == NULL)
{
printf("Error\n");
return 1;
}
fscanf(file, "%d %d\n", &primNum, &secNum);
printf("\n1st Number: %d",primNum);
printf("\n2nd Number: %d",secNum);
printf("List of Numbers");
for(i=0;i<numberOfLines;i ){
//Count the number from the second line onwards
}
fclose(file);
return 0;
}
uj5u.com熱心網友回復:
您只需要一個回圈來繼續讀取intsfile并填充listOfNumers陣列,直到讀取int失敗。
由于您不知道檔案中有多少ints,因此您也可以動態分配記憶體。例子:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE* file = fopen("file.txt", "rt");
if(file == NULL) {
perror("file.txt");
return 1;
}
int primNum;
int secNum;
if(fscanf(file, "%d %d", &primNum, &secNum) != 2) {
fprintf(stderr, "failed reading primNum and secNum\n");
return 1;
}
unsigned numberOfLines = 0;
// allocate space for one `int`
int* listOfNumers = malloc((numberOfLines 1) * sizeof *listOfNumers);
// the above could just be:
// int* listOfNumers = malloc(sizeof *listOfNumers);
while(fscanf(file, "%d", listOfNumers numberOfLines) == 1) {
numberOfLines;
// increase the allocated space by the sizeof 1 int
int* np = realloc(listOfNumers, (numberOfLines 1) * sizeof *np);
if(np == NULL) break; // if allocating more space failed, break out
listOfNumers = np; // save the new pointer
}
fclose(file);
puts("List of Numbers:");
for(unsigned i = 0; i < numberOfLines; i) {
printf("%d\n", listOfNumers[i]);
}
free(listOfNumers); // free the dynamically allocated space
}
uj5u.com熱心網友回復:
有幾種方法可以解決這個問題;如果你知道第一行的大小,你應該能夠使用fseek移動檔案的位置而不是使用getline獲取檔案的每一行:
int fseek(FILE *stream, long offset, int whence);
whence引數可以是:
SEEK_SET: 開始SEEK_CUR: 當前位置SEEK_END: 結束
另一種選擇是將讀取的整個檔案封裝在一個while回圈中:
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
int counter = 0;
while((linelen = getline(&line, &linecap, file)) != -1){
if counter == 0{
sscanf(line, "%d %d\n", &primNum, &secNum);
}else{
//Process your line
}
counter ; //This would give you your total line length
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/497973.html
