C语言文件内容转置
时间: 2023-07-04 11:04:53 浏览: 57
以下是将文件内容进行转置的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 100
int main() {
char file_name[100];
printf("Enter the name of the file to transpose: ");
scanf("%s", file_name);
FILE *input_file = fopen(file_name, "r");
if (input_file == NULL) {
printf("Unable to open file!");
return 1;
}
char output_file_name[100];
printf("Enter the name of the output file: ");
scanf("%s", output_file_name);
FILE *output_file = fopen(output_file_name, "w");
if (output_file == NULL) {
printf("Unable to create output file!");
return 1;
}
char line[MAX_LINE_LENGTH];
int max_line_length = 0;
int line_count = 0;
// Read the input file and determine the maximum line length and number of lines
while (fgets(line, MAX_LINE_LENGTH, input_file) != NULL) {
int current_length = strlen(line);
if (current_length > max_line_length) {
max_line_length = current_length;
}
line_count++;
}
// Allocate memory for the transposed matrix
char **transpose = (char **) malloc(max_line_length * sizeof(char *));
for (int i = 0; i < max_line_length; i++) {
transpose[i] = (char *) malloc(line_count * sizeof(char));
}
// Reset the file pointer to the beginning of the file
rewind(input_file);
// Transpose the matrix
for (int i = 0; i < line_count; i++) {
fgets(line, MAX_LINE_LENGTH, input_file);
int current_length = strlen(line);
for (int j = 0; j < current_length; j++) {
transpose[j][i] = line[j];
}
}
// Write the transposed matrix to the output file
for (int i = 0; i < max_line_length; i++) {
for (int j = 0; j < line_count; j++) {
if (transpose[i][j] != '\0') {
fprintf(output_file, "%c", transpose[i][j]);
} else {
fprintf(output_file, " ");
}
}
fprintf(output_file, "\n");
}
// Free the memory allocated for the transposed matrix
for (int i = 0; i < max_line_length; i++) {
free(transpose[i]);
}
free(transpose);
// Close the input and output files
fclose(input_file);
fclose(output_file);
printf("File transposed successfully!");
return 0;
}
```
代码的大致思路是先读入文件,然后确定文件中最长的一行有多少个字符,以及文件中共有多少行。接着,动态分配一个二维字符数组,用于存储转置后的矩阵。然后,再次读取文件内容,将每一行中的字符存储到转置矩阵对应的位置上。最后,将转置矩阵输出到指定的输出文件中即可。