在C中从文本文件拆分和修改字符串

时间:2018-12-07 21:23:40

标签: c arrays string

在一个学校项目中,我正在制作凯撒密码。我要满足的要求如下:我需要从文本文件中读取文本,并将其存储到字符串的二维数组中,每行最多包含81个字符(80个有用的+'\ 0')和1000行,然后修改内容以对其进行加密或解密。如果文件中的一行文本中有80个以上有用字符怎么办?我考虑过以某种方式读取它,使其读取的每个空间都将其转换为'\ 0'并更改数组中的行,但是我不知道是否可以使用fgets代替它,而不是像我那样做的fgetc

这就是我现在拥有的:

int lerficheiro(char * texto[MAXLINHAS][MAXCARPORLINHA])
{
    char caractere;
    FILE * fp;
    fp = fopen("tudomaiusculas.txt", "r");
    if(fp==NULL)
    {
        printf("Erro ao ler ficheiro.");
        return (-1);
    }
    for(int linha = 0; linha < MAXLINHAS; linha++)
    {
        for(int coluna = 0; coluna < MAXCARPORLINHA; coluna++)
        {
            caractere = fgetc(fp);
            if(caractere == ' ') caractere = '\0'; break;
            if(caractere == '\n') caractere = '\0'; break;
            if(caractere < 'A' || caractere > 'Z')
            {
                printf("Erro ao ler, o ficheiro não contem as letras todas 
maiusculas");
                return (-1);
            }
            * texto[linha][coluna] = caractere;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将数组初始化为0,并利用选择使用fgets读取多少字节这一事实。只需检查fgets的返回值即可查看是否已到达文件末尾。
还要注意,您不必将结果数组作为指针,因为数组已经是指针(编辑以镜像@ user3629249建议) EDIT2:编辑代码以考虑换行问题。 Alo删除了导致79个字符行的-1而不是80

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

#define MAX_LINES 8000
#define HSIZE 81

int parse_file( FILE * inp_file, char res[MAX_LINES][HSIZE])
{
    int l = 0;
    int len = HSIZE;
    while( fgets( res[l]+(HSIZE-len), len, inp_file ))
    {
        len = HSIZE - strlen( res[l]);
        if( len <= 1)
        {
            l++;
            len = HSIZE;
        }
    }
}

int main()
{
    char parsed_file[MAX_LINES][HSIZE] = {0};

    FILE * inp_file;

    inp_file = fopen( "file_to_parse.txt", "r");
    if( inp_file == NULL)
    {
        printf( "Failed to read input file...\n");
        return 1;
    }

    parse_file( inp_file, parsed_file);

    fclose( inp_file);

    for( int i=0; parsed_file[i][0] != 0; i++)
        printf( "line %04d: %s\n", i+1,parsed_file[i]);

    return 0;
}

如果您愿意,还可以用以下内容替换parsed_file中的新行

char *pos;
while( (pos = strchr( line, '\n'))
    *pos = ' ';

带有测试文件:

This is a random file that I'm testing out for the pure randomness of random files.
Still reading, m'kay man lets get going!!!!!!!!!!! So last day the craziest thing happened, let me tell you about it....

并输出

line 0001: This is a random file that I'm testing out for the pure randomness of random fil
line 0002: es.
Still reading, m'kay man lets get going!!!!!!!!!!! So last day the craziest 
line 0003: thing happened, let me tell you about it....

请注意,printf仍将打印换行符