编写一个程序,将一个文件中的每一行添加行号,并输出至原文件中
输入形式:文本文件
输出形式:为每一行增加行号
测试用例:
输入:abcdef abc
abcdefghi
输出:1abcdef abc
2abcdefghi
先按行将内容读取到内存中,然后关闭读取流,遍历向文件中写入。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[101][101];
FILE *fp = fopen("data.txt", "r");
if (!fp) {
printf("本地数据文件不存在\n");
return -1;
}
int i=0;
while(!feof(fp))
{
fgets(str[i], sizeof(str[i]), fp);
i++;
}
fclose(fp);
//写入文件
FILE *fp2 = fopen("data.txt", "w");
for(int j=0;j<i;j++){
fprintf(fp2, "%d%s", j+1, str[j]);
}
fclose(fp2);
return 0;
}
完整的代码实现如下,望采纳
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LEN 80 // 行最大长度
int main()
{
char line[MAX_LINE_LEN]; // 存储当前行
int line_num = 1; // 行号从 1 开始
FILE *fp; // 文件指针
// 以写入方式打开文件
if ((fp = fopen("input.txt", "w")) == NULL) {
printf("无法打开文件\n");
exit(EXIT_FAILURE);
}
// 循环读取输入的每一行
while (fgets(line, MAX_LINE_LEN, stdin) != NULL) {
// 在每一行的开头添加行号
fprintf(fp, "%d %s", line_num, line);
line_num++; // 行号递增
}
fclose(fp); // 关闭文件
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Open the input and output files
ifstream in("input.txt");
ofstream out("output.txt");
// Read the input file line by line
string line;
int line_number = 1;
while (getline(in, line)) {
// Add the line number to the beginning of the line
out << line_number << " " << line << endl;
line_number++;
}
// Close the files
in.close();
out.close();
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!