linux文件编程:fread fwrite

xiaoxiao2021-02-28  114

已知

file1                         file2                             

x1 x2 x3... y1 y2 y3...

x4 x5 x6... y4 y5 y6...

................                  .................

file1 and file2行数列数相同

编程建立

file3

z1 z2 z3....

z4 z5 z6....

..................

满足zn = xn + yn

note

1.EOF  is an indicator, a const int ,default set as -1

2.feof is a function --  int feof(FILE * stream)

returning an non-zero indicator(which is equal to EOF) if reach the end of file,else return 0.

3.a way to turn char into int

char a; //set as what you want

int b = a - '0';

#include<stdio.h> int readfile(const char *, int *, int *, int *); void writefile(const char *, int, int, int*); int main() { int mrow, mcol; int all; int num1[100] = {0}; int num2[100] = {0}; int num3[100] = {0}; int count = 0; all = readfile("./file1", &mrow, &mcol, num1); readfile("./file2", &mrow, &mcol, num2); printf("all = %d\n", all); for(count = 0; count <= all; count++) { num3[count] = num1[count] + num2[count]; } writefile("./file3", mrow, mcol, num3); return 0; } void writefile(const char * path, int mrow, int mcol, int* num3) { FILE *fp = fopen(path, "w"); if(fp == NULL) { perror("writefile"); return; } int cr = 0, cc = 0; int c = 0; while(num3[c] != 0) { for(cr = 0; cr < mrow; cr++) { for(cc = 0; cc <= mcol; cc++) { fprintf(fp, "%d", num3[c]); c++; if(cc != mcol) { fprintf(fp, " "); } } fprintf(fp, "\n"); } } fclose(fp); return; } int readfile(const char * path, int * mrow, int * mcol, int num1[]) { FILE * fd = fopen(path, "r"); if(fd == NULL) { perror("open file1"); return 1; } char c; char buf1[100]; int i = 0; while((c = fgetc(fd)) != EOF) { buf1[i] = c; i++; } i = 0; int a = 0; int t = 0; int col = 0; int row = 0; int flag = 0; while(buf1[i + 1] != '\0') { if(buf1[i] == ' ') { a++; i++; if(flag == 0) { col++; } continue; } if(buf1[i] == '\n') { a++; i++; row++; flag = 1; continue; } t = buf1[i] - '0'; num1[a] = 10 * num1[a]; num1[a] = num1[a] + t; i++; } *mrow = row; *mcol = col; fclose(fd); return a; }

转载请注明原文地址: https://www.6miu.com/read-59793.html

最新回复(0)