下面是一个示例程序,可以用字节方式打开一个文件,从头开始搜索字符串"abcde",并打印出该字符串的位置和字符串后面的4个字节数据:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int position;
    char data[5];
} SearchResult;

SearchResult searchFile(const char* filename, const char* searchString) {
    FILE* file = fopen(filename, "rb");
    if (file == NULL) {
        perror("Failed to open file");
        SearchResult result = {-1, ""};
        return result;
    }

    SearchResult result = {-1, ""};
    int searchStringLength = strlen(searchString);
    char buffer[searchStringLength + 4];

    int currentPosition = 0;
    while (fread(buffer, sizeof(char), searchStringLength + 4, file) == searchStringLength + 4) {
        if (memcmp(buffer, searchString, searchStringLength) == 0) {
            result.position = currentPosition;
            memcpy(result.data, buffer + searchStringLength, 4);
            result.data[4] = '\0';
            break;
        }
        currentPosition++;
        fseek(file, currentPosition, SEEK_SET);
    }

    fclose(file);
    return result;
}

int main() {
    const char* filename = "example.txt";
    const char* searchString = "abcde";

    SearchResult result = searchFile(filename, searchString);
    if (result.position != -1) {
        printf("Found at position: %d\n", result.position);
        printf("Data after string: %s\n", result.data);
    } else {
        printf("String not found in file\n");
    }

    return 0;
}

请注意,这里假设文件是以二进制方式打开的,因此搜索会以字节为单位进行。在搜索过程中,每次读取searchStringLength + 4个字节的数据,然后使用memcmp函数比较读取的数据与目标字符串是否匹配。如果找到匹配的字符串,就将位置记录在result结构体中,并将后面的4个字节数据复制到result结构体的data数组中。最后,程序会打印出位置和数据。

请将上述代码保存为一个.c文件,然后编译并运行它,即可搜索指定文件中的字符串"abcde"。请确保将文件名和搜索字符串替换为实际的值

假设你是一个程序员写一个程序用字节方式打开一个文件从头开始搜索字符串abcde搜到后打印出这个字符串的位置和字符串后面4字节数据以结构体方式处理

原文地址: http://www.cveoy.top/t/topic/iJHk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录