How to print text with formatting

My problem is that when I try to print text using "\ n", these special characters are invisible to printf and put after the echo in the file and read again.

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

int main()
{   
    FILE *f;
    char *s = (char*) malloc (2919);
    strcpy(s, "printf 'H4sIAIM4aFYCAwtJLS6JyQsBklwAMrDLnwsAAAA=' | base64 -d | gunzip > r"); //Test\nTest after decoding
    system(s);
    f = fopen("r", "r");
    fseek(f, SEEK_SET, 0);
    fread(s, 2919, 1, f);
    printf("%s", s); //puts(s); gives the same result
    fclose(f);
    system("rm r");
    free(s);
    return 0;
}

The result should look like this:

Test
Test

and looks like Test\nTest. What am I doing wrong? The purpose of the training, so please be kind.

+4
source share
5 answers

Your code has the following problems:

  • fseek(f, SEEK_SET, 0);it makes no sense, a file opened with fopen, by default, is the default.

  • fread(s, 2919, 1, f);: You do not store the number of bytes read. You cannot correctly zero the end of the buffer for printf to stop at the last decoded byte. How do you know the file size anyway?

  • H4sIAIM4aFYCAwtJLS6JyQsBklwAMrDLnwsAAAA= Test\nTest lteral \, n, . r fread escape- \n . . , .

:

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

int main(void) {   
    FILE *f;
    char *s = malloc(2919 + 1);
    char *p;
    int nread;

    strcpy(s, "printf 'H4sIAIM4aFYCAwtJLS6JyQsBklwAMrDLnwsAAAA=' | base64 -d | gunzip > r"); //Test\nTest after decoding
    system(s);
    f = fopen("r", "r");
    nread = fread(s, 2919, 1, f);
    if (nread >= 0) {
        s[nread] = '\0';
        while ((p = strstr(s, "\\n")) != NULL) {
            /* converting \ n sequences to linefeed characters */
            *p = '\n';
            memmove(p + 1, p + 2, strlen(p + 2) + 1);
        }
        printf("%s", s); //puts(s); will not give the same result
    }
    fclose(f);
    system("rm r");
    free(s);
    return 0;
}
+3

, , :

Test\nTest

10- "\" "n" . :

char str[]="Test\nTest";

9- .

, . , .

+4

, , '\' 'n' .

,

  • :

    $ echo $'Test\nTest' | gzip | base64
    H4sIAEs+aFYAAwtJLS7hCgERAF0muOIKAAAA
    $ echo $'Test\nTest' | gzip -n | base64
    H4sIAAAAAAAAAwtJLS7hCgERAF0muOIKAAAA
    
  • - \n . .

+2

@lurker ...

, , . escape-: "echo -e $(printf 'H4sIAIM4aFYCAwtJLS6JyQsBklwAMrDLnwsAAAA =' | base64 -d | Gunzip) "

- , , ASCII ( UTF-8):

T  e  s  t  \  n  T  e  s  t

, () ( \n), \ n.

gzipped-. . , gzipped - , .

, @lurker, - , \ n - .

, . , :

Test
Test

... , .

, :

Test\nTest

... ( -n), , -, , .

?

+2

C "\n" (ASCII- 10) (, ), .

:

char s1[] = "TEST\nTEST";
printf(s1); // ---> TEST newline TEST.

char s2[] = "TEST\\nTEST"; // s2 = "TEST\nTEST"
printf(s2); // ---> TEST\nTEST (the characters \ and n are present inside the string)

, s1 C, \n . escape- \ , s2 TEST\nTEST, ( ), , , , .

, printf(s2) printf("TEST\nTEST"), , C , \n newline.

+2

Source: https://habr.com/ru/post/1619217/


All Articles