C语言获取文件中一行数据,并将该行删除

统计文件中的行数如下:

int count_file_row(char *path)
{    
    int lines = 1;
    FILE *fp = NULL;

    fp = fopen(path, "r");
    while(!feof(fp))
    {
        ch = fgetc(fp);
        if(ch == '\n')
        {
            lines++;
        }
    }
    printf("line row: %d\n", lines);
    fclose(fp);
    return lines;
}

从文件中读取一行常用函数:

char *fgets(char *s, int size, FILE *stream);

fgets()  reads  in  at  most one less than size characters from stream and stores them into the buffer pointed to by s.  Reading stops after an EOF or a newline.  If a newline is read, it is stored into the buffer.  A terminating null byte ('\0') is stored after the last character in the buffer.

从文件中读取制定行:

static int get_assigned_row(char *path, char *line, int len, int assign_line)
{
    int lines = 1;
    FILE *fp = NULL;

    fp = fopen(path, "r");
    if (fp == NULL) {
        printf("open %s failed!\n", path);
        return -1;
    }

    while (fgets(line, len, fp) != NULL)
    {
        if (lines == assign_line) {
            break;
        }
        ++lines;
        memset(line, 0, len);
    }
    //printf("line: %s\n", line);

    if (fclose(fp) != 0) {
        printf("close file %s failed!\n", path);
        return -2;
    }
    return 0;
} 

删除文件中的制定行:

#define ONE_ROW_MAX_CHR 256
static int del_assigned_row(char *path, int assign_line)
{
    int lines = 1;
    char path_tmp[256] = {0};
    char line[ONE_ROW_MAX_CHR] = {0};
    FILE *fp_in = NULL, *fp_out = NULL;

    sprintf(path_tmp, "%s.tmp",path);
    fp_in = fopen(path, "r");
    if (fp_in == NULL) {
        printf("open %s failed!\n", path);
        return -1;
    }
    fp_out = fopen(path_tmp, "a+"); 
    if (fp_out == NULL) {
        printf("create tmp file %s failed!\n", path_tmp);
        return -1;
    }

    while (fgets(line, ONE_ROW_MAX_CHR , fp_in) != NULL)
    {
        if (lines != assign_line) {
            fwrite(line, 1, strlen(line), fp_out);
        }
        ++lines;
        memset(line, 0 , ONE_ROW_MAX_CHR );
    }

    if (fclose(fp_in) != 0) {
        printf("close file %s failed!\n", path);
        return -2;
    }
    if (fclose(fp_out) != 0) {
        printf("close file %s failed!\n", path_tmp);
        return -2;
    }
    remove(path);
    rename(path_tmp, path);

    return 0;
}

你可能感兴趣的:(C++/C)