.Linux平台下利用系统接口函数按照行读写文件;支持文件定位读写,读写位置(行,字符)通过参数传递。
时间: 2024-04-09 09:28:09 浏览: 40
在Linux平台下,你可以使用系统接口函数来按行读写文件,并支持文件定位读写。以下是一个示例代码,展示了如何通过参数传递读写的位置(行,字符)。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readFromFile(const char* filename, int line, int character) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return;
}
char buffer[256];
int currLine = 1;
int currChar = 0;
while (fgets(buffer, sizeof(buffer), file)) {
if (currLine == line) {
int len = strlen(buffer);
if (currChar < len) {
printf("Read from line %d, character %d: %c\n", line, character, buffer[currChar]);
break;
}
else {
printf("Character position exceeds line length.\n");
break;
}
}
currLine++;
}
fclose(file);
}
void writeToFile(const char* filename, int line, int character, char data) {
FILE* file = fopen(filename, "r+");
if (file == NULL) {
printf("Failed to open the file.\n");
return;
}
char buffer[256];
int currLine = 1;
int currChar = 0;
while (fgets(buffer, sizeof(buffer), file)) {
if (currLine == line) {
int len = strlen(buffer);
if (currChar < len) {
buffer[currChar] = data;
fseek(file, -len, SEEK_CUR);
fputs(buffer, file);
printf("Write to line %d, character %d: %c\n", line, character, data);
break;
}
else {
printf("Character position exceeds line length.\n");
break;
}
}
currLine++;
}
fclose(file);
}
int main() {
const char* filename = "test.txt";
int line = 3;
int character = 4;
readFromFile(filename, line, character);
char newData = 'X';
writeToFile(filename, line, character, newData);
readFromFile(filename, line, character);
return 0;
}
```
上述代码中,`readFromFile` 函数用于从指定文件中读取指定位置的字符,`writeToFile` 函数用于向指定文件中的指定位置写入字符。在 `main` 函数中,我们可以设置文件名、行数、字符位置等参数,并进行读写操作。
注意:在使用这段代码之前,你需要创建一个名为 `test.txt` 的文本文件,并在其中填入一些内容。
阅读全文