救命!这怎么成图片里的那样,只删除独立一行的啊 弄出来的都是全部删除了啊,这怎么办啊。
如果你想在 C 语言中删除单独一行,可以使用文件操作函数来实现。以下是一个例子:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp1, *fp2;
char file_name[100], temp[1000];
int line_no, count = 0;
printf("Enter the name of file: ");
scanf("%s", file_name);
fp1 = fopen(file_name, "r"); // 打开要读取的文件
if (fp1 == NULL) {
printf("File not found.\n");
return 0;
}
fp2 = fopen("temp.txt", "w"); // 打开一个临时文件进行写入
if (fp2 == NULL) {
printf("Error creating temporary file.\n");
fclose(fp1);
return 0;
}
printf("Enter the line number to be deleted: ");
scanf("%d", &line_no);
while (fgets(temp, 1000, fp1)) { // 逐行读取文件
count++;
if (count != line_no) { // 判断是否为要删除的行
fputs(temp, fp2); // 如果不是则写入临时文件
}
}
fclose(fp1);
fclose(fp2);
remove(file_name); // 删除原文件
rename("temp.txt", file_name); // 重命名临时文件为原文件名
printf("Line %d deleted successfully!\n", line_no);
return 0;
}
这个程序的思路是,首先要求用户输入要删除的行数,然后逐行读取文件并将其写入一个临时文件中,但不写入要删除的行,最后将临时文件重命名为原文件名,就相当于删除了单独一行。
【以下回答由 GPT 生成】
我会使用Python编写一个脚本来解决这个问题。以下是解决问题的步骤:
下面是实现这个解决方案的Python代码:
# 读取源文件
with open("input.c", "r") as file:
lines = file.readlines()
# 删除单独占行注释
cleaned_lines = []
for line in lines:
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith("//") and not stripped_line.startswith("/*") and not stripped_line.endswith("*/"):
cleaned_lines.append(line)
# 将修改后的内容保存到输出文件
with open("output.c", "w") as file:
file.writelines(cleaned_lines)
请将源文件保存为input.c
,然后运行上述代码,将会生成一个名为output.c
的文件,其中包含已删除单独占行注释后的内容。
【相关推荐】