như tiêu đề, data được e dùng bộ nhớ động để lưu trên pointer mảng. sau đó e viết vào file binary.
nhưng khó là do ng khác khi lấy data không biết kích thước của mảng nên em tạo 1 con trỏ mảng khác để lưu dữ liệu. vấn đề ở đây là e không tài nào in ra nổi nội dung em đã viết. đây là code của em:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"include <stdio.h>
#include <stdlib.h>
int main() {
char filename[10];
FILE* pFile;
long lSize;
char* buffer;
size_t result;
char *arr[10];
int i;
printf("enter filename: "); // nhập tên file rồi tạo luôn
scanf("%s", filename);
char buff[10];
for(i=0;i<10; i++){ // lấy kí tự từ người nhập
printf("%02d번째 단어 입력: ", i+1);
scanf("%s", buff);
arr[i] = (char *)calloc(strlen(buff)+1, sizeof(char));
strcpy(arr[i], buff);
}
pFile = fopen(filename, "wb+");
if (pFile == NULL) {
fputs("File error", stderr);
exit(1);
}
fwrite(arr, sizeof(arr), 1, pFile); // truyền mảng arr vào file
// kích thước được lưu vào lSize
fseek(pFile, 0, SEEK_END);
lSize = ftell(pFile); // lấy kích thước của file
rewind(pFile);
buffer = (char*)malloc(sizeof(char) * lSize);
if (buffer == NULL) {
fputs("Memory error", stderr);
exit(2);
}
// đọc nội dung
result = fread(buffer, 1, lSize, pFile);
if (result != lSize) {
fputs("Reading error", stderr);
exit(3);
}
char sen[1000];
// fprintf(pFile, "%s", sen); em định dùng fprintf để lấy data nhưng thôi
// fscanf(pFile, "%[^\n]", sen);
strcpy(sen, buffer);
printf("%s", sen);
fclose(pFile);
free(buffer);
return 0;
}
không rõ sao mà không thể lấy thông tin được!
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?