1、数组
#include <stdio.h> #include <stdlib.h> #define BUF_SIZE 100 #define MAX_SIZE 100 int main() { int **arr; int rows, cols; int rows_size, cols_size = 5; int num, i = 0; int arr_size = 0; FILE *fp = NULL; fp = fopen("filename.txt", "r"); // open file and read data if (fp != NULL) { printf("open file success\n"); rows = 0; cols = 0; while (fscanf(fp, "%d", &num) == 1) { i++; if (i % cols_size == 0) { rows++; } } if (i % cols_size != 0) { rows++; } rows_size = rows; arr_size = i; printf("data count is %d\n", i); printf("rows is %d\n", rows_size); // dynamic allocate memory arr = (int **)calloc(rows_size, sizeof(int *)); for (i = 0; i < rows; i++) { arr[i] = (int *)calloc(cols_size, sizeof(int)); } fp = fopen("filename.txt", "r"); if (fp != NULL) { i = 0; while (fscanf(fp, "%d", &num) == 1) { if (i < arr_size) { arr[i / cols_size][i % cols_size] = num; i++; } } } fclose(fp); // print data printf("the data from file is:\n"); for (i = 0; i < rows_size; i++) { for (int j = 0; j < cols_size; j++) { printf("%d ", arr[i][j]); } printf("\n"); } // free memory for (i = 0; i < rows_size; i++) { free(arr[i]); } free(arr); } else { printf("open file failed\n"); return 0; } // close file if (fclose(fp) == 0) { printf("close file success\n"); } else { printf("close file failed\n"); } return 0; }
2、结构体
#include <stdio.h> #include <stdlib.h> #define BUF_SIZE 100 #define MAX_SIZE 100 int main() { // char buf[BUF_SIZE]; typedef struct _sPerson { int num; char name[MAX_SIZE]; char email[MAX_SIZE]; int phone; } sPerson; sPerson *ps = (sPerson *)(malloc(sizeof(sPerson))); FILE *fp = NULL; fp = fopen("./data_structure.txt", "r"); if (fp != NULL) { printf("open file success\n"); while (fscanf(fp, "%d %s %s %d", &(ps->num), ps->name, ps->email, &(ps->phone)) == 4) { printf("%d %s %s %d\n", ps->num, ps->name, ps->email, ps->phone); } } else { printf("open file failed\n"); return -1; } // close file if (fclose(fp) == 0) { printf("close file success\n"); } else { printf("close file failed\n"); } free(ps); return 0; }
标签:语言,fp,file,rows,读取,int,数组,printf,size From: https://www.cnblogs.com/dogingate/p/17849674.html