linux c 修改文件某一行的值代码示例
时间: 2024-09-14 16:10:45 浏览: 54
Python实现生成简单的Makefile文件代码示例
在Linux环境下,使用C语言直接修改文件内容通常涉及到文件I/O操作,特别是当文件较大并且需要处理行级别的数据时,可以采用逐行读取、修改后再写回的方式。这里有一个简单的示例,假设我们要修改一个文本文件中的特定行:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 100
void replace_line_in_file(const char *filename, int line_num, const char *new_content) {
FILE *file = fopen(filename, "r+");
if (file == NULL) {
perror("Failed to open file");
return;
}
char line[MAX_LINE_LENGTH];
size_t line_count = 0;
while (!feof(file)) {
size_t bytes_read = fread(line, sizeof(char), MAX_LINE_LENGTH, file);
if (bytes_read > 0 && fgets(line + bytes_read, MAX_LINE_LENGTH - bytes_read, file) != NULL) { // Read a line
++line_count;
// If we found the line to modify
if (line_count == line_num) {
fseek(file, 0, SEEK_SET); // Reset position to beginning of the file
fprintf(file, "%s", new_content); // Write the new content
fseek(file, 0, SEEK_END); // Go back to end after writing
break; // We don't need to read further
}
} else {
break;
}
}
fclose(file);
if (line_count < line_num) {
printf("Line %d not found.\n", line_num);
}
}
// 使用示例
int main() {
const char *filename = "test.txt";
int line_number_to_replace = 5;
char new_line[] = "New value for this line";
replace_line_in_file(filename, line_number_to_replace, new_line);
阅读全文