How do I replace line-by-line text of a file in C?

Jaffar Ali

I have been researching this for a while and haven't been able to find anything that helps my specific case.

I have a function in which I need to encrypt text in a file. What I want to do is to read a line from a text file and store it into a string, run an encryption algorithm on the string and write the encrypted content of the string back into to the file. That is, I want to replace the file's current line with the encrypted line.

Here is what I have so far:

int encrypt_file(char file_name[]) {
    FILE* file = fopen(file_name, "r+");

    if (file) {
        char line[300];
        while ((fgets(line, sizeof(line), file)) != NULL) {
            fseek(file, -(strlen(line)), SEEK_CUR);
            encrypt_string(line);
            if (fputs(line, file) == EOF) {
                printf("Error. Please try again.\n");
                fclose(file);
                return 1;
            }
        }
        fclose(file);
        return 0;
    } else {
        printf("Error. Ensure file exists and try again.\n");
        return 1;
    }
    fclose(file);
    return 0;
}

To explain my logic, I read the line from the file and then use fseek to move the pointer back by however many characters were read (it should now be at the beginning of the line). I then run the algorithm and then write the new string back into the file.

However, this code gives me an infinite loop. When I remove the fseek, it doesn't give me an infinite loop and it shows me that the algorithm has been correctly used on the string, but it shows the "Error. Please try again.\n" response and no changes have been made to the file itself.

Any help is appreciated.

Jaffar Ali

There was an answer posted here that helped solve my issue. I'm not sure why it has been deleted but if anyone was wondering, it was suggested that I use ftell to keep track of where the pointer should be. This is the code I have now, and it works as intended (the #ifdef statements were just to find out what was going wrong, and are not necessary for the code to work):

int encrypt_file (char file_name[]) {
    FILE* file = fopen(file_name, "r+");
    long fileindex = 0;

    if (file) {
        char line[300];
        while ((fgets(line, sizeof(line), file)) != NULL) {
            #ifdef DEBUG
                printf("Input: %s", line);
                char* p = strchr(line, '\n');
                if (!p) {
                    printf("\n");
                }
            #endif

            fseek(file, fileindex, SEEK_SET);
            encrypt_string(line);

            #ifdef DEBUG
                printf("Output: %s\n", line);
            #endif

            if (fputs(line, file) == EOF) {
                printf("Error. Please try again.\n");
                fclose(file);
                return 1;
            }
            fileindex = ftell(file);
            fseek(file, 0, SEEK_CUR);
        }
        fclose(file);
        return 0;
    }
    else {
        printf("Error. Ensure file exists and try again.\n");
        return 1;
    }

    fclose(file);
    return 0;
}

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How do I replace a line in a file using PowerShell?

How do I loop though a text file, line by line, and append each line to an array?

How do I separate a each text file line into a separate lists?

How do I read two strings on each line, line by line, from a file in C

How to read file line by line and print to a text box c#

Python How to replace a particular word in a particular line in a text file?

Write into text file line by line c

How do I replace only a group of empty lines by an empty line?

How do I replace a json comma with a new line

How do I save variables to a text file to a new line each time?

How to read text file line by line?

how to read text file line to line in python

PHP : How to Replace some text from n th line to m th line from file?

How do I get this file the first number of each line to increment it? And what about the first line not being skipped? In C

How do I end the program once the last line of the text is reached?

How do I append text to the line containing a substitution in Perl?

how do i align my th text in a same line

If I add the same product twice from a text file how do I output it one one line with the product price added together?

How to count in which line in text file the word is C++

How can I switch the position of a line with the line after it in a text file using a Scanner?

How to replace a specific line in a file using Java?

How do i make python choose randomly one line after the first line of a file?

How do i make python choose randomly one line after the first line of a file?

saving a text file into a linked list line by line in c

Append text to file with new line c++

Laravel 5.6 how to read text file line by line

How Would I Check if a Text File Contains Specified Text and Report what Line it is At

How do I replace an entire line that matches several words in Powershell regex?

Edit php to replace a line of text

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo