我在将结果保存到输出文件时遇到问题。该功能可能有问题,但我找不到并修复它。有人知道出了什么问题吗?
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int **str;
int *tab;
void read(){
int n = 1;
char help_sign;
FILE *fp = fopen("In0303.txt", "r");
if(fp == NULL){
printf("Blad odczytu z pliku!");
}
while((help_sign = fgetc(fp)) != EOF){
if (help_sign == '\n'){
n++;
}
}
fclose(fp);
}
void gen(){
int i, n;
int **str;
str =(int**)malloc(n*sizeof(int*));
for (i = 0; i < n; i++){
str[i] = (int*)malloc(4*sizeof(int));
}
}
void load_date(){
int i, n;
int **str;
FILE *fp = fopen("In0303.txt", "r");
for (i = 0; i < n; i++){
fscanf(fp, "%d" , &str[i][0]);
fscanf(fp, "%d" , &str[i][1]);
fscanf(fp, "%d" , &str[i][2]);
str[i][3]=0;
}
fclose(fp);
}
void gen_tab(){
int i, n, k = 0;
int **str;
int *tab;
for (i = 0; i < n; i++){
if (str[i][0] > k) k = str[i][0];
if (str[i][1] > k) k = str[i][1];
}
tab = (int*)malloc(k*sizeof(int));
for (i = 0; i < k; i++){
tab[i] = i + 1;
}
}
void sort(){
int i, n, j,tmp;
int **str;
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++){
if (str[i][2] > str[j][2]){
tmp = str[i][0];
str[i][0] = str[j][0];
str[j][0] = tmp;
tmp = str[i][1];
str[i][1] = str[j][1];
str[j][1] = tmp;
tmp = str[i][2];
str[i][2] = str[j][2];
str[j][2] = tmp;
}
}
}
int min(int x, int y){
if (x > y) return y;
else return x;
}
int max(int x, int y){
if (x < y) return y;
else return x;
}
void make(){
int i, j, min1, max1, p, q, n, k;
int *tab;
int **str;
for (i = 0; i < n; i++){
if (tab[((str[i][0])-1)] != tab[((str[i][1])-1)]){
str[i][3] = 1;
min1 = min(tab[((str[i][0])-1)], tab[((str[i][1])-1)]);
max1 = max(tab[((str[i][0])-1)], tab[((str[i][1])-1)]);
for (j = 0; j < k; j++){
if (tab[j] == max1)
tab[j] = min1;
}
}
}
}
void save(){
int i, n;
int **str;
int *tab;
FILE *g = fopen("Out0303.txt","w");
for (i = 0; i < n; i++){
if (str[i][3] == 1){
fprintf(g, "%d ", str[i][0]);
fprintf(g, "%d ", str[i][1]);
fprintf(g, "%d\n", str[i][2]);
}
}
fclose(g);
}
int main(){
read();
gen();
load_date();
gen_tab();
sort();
make();
save();
printf("Wyniki zapisane do pliku!\n");
free(str);
free(tab);
return 0;
}
这是输入文件(“In0303.txt”):
9 17
2 3 8 4 9 8
1 3 3 6 4 5 9 6
2 6 4 4 9 1
2 5 3 4 5 3 9 2
4 3 6 1 9 5
5 1 7 5 9 2
6 5 8 4 9 2
1 4 7 4 9 2
1 8 2 6 3 1 4 2 5 5 6 2 7 2 8 2
这就是应该在输出文件中创建的内容:(“Out0303.txt”):
17
3 9 [1]
5 6 [1]
4 9 [2]
6 9 [2]
7 9 [2]
8 9 [2]
1 2 [3]
1 8 [4]