-1

I'm trying to copy text from a input.txt but programs thinks spaces are new lines. How should I go about this?

my input.txt (trial)

1. hero
2. angelic
3. hello world
4. demons

my source.c

int main(void) {

FILE* fread = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");

if (fread == NULL) {
    printf("One file wouldn't open!\n");
    return -1;
}

    //this pastes the text from input.txt into the command-line
char line[1000] = "";
while (fscanf(fread, "%s", line) == 1) {
    printf("%s\n", line);
}

fclose(fread);
fclose(fwrite);

output

1.
hero
2.
angelic
3.
hello
world
4.
demons
JohnDoe12
  • 35
  • 5
  • Does this answer your question? [C read file line by line](https://stackoverflow.com/questions/3501338/c-read-file-line-by-line) – kotatsuyaki Jan 09 '23 at 09:39
  • Preferably, you should use `fgets` instead of `scanf`. `%s` modifier will stop reading at the first whitespace character it encounters, you could use `%[^\n]` instead to read the whole line. – alex01011 Jan 09 '23 at 09:39
  • And you should definitely limit the input length, since your array is of `char [1000]`, `%999[^\n]` should do it. – alex01011 Jan 09 '23 at 09:43
  • @alex01011 you mean `"%999[^\n]%*c"` or with a space before the %: `" %999[^\n]"` isn't it? Otherwise the newline is not consumed and only the first line is printed. – David Ranieri Jan 09 '23 at 09:47
  • Yes, space in front is required you are right. – alex01011 Jan 09 '23 at 09:52
  • 1
    Using variables named `fread` and `fwrite` in a function that does file operations feels rather inappropriate, if you ask me – mmixLinus Jan 09 '23 at 09:58

1 Answers1

1

Here is what you do. There is already function implemented to help you in doing this.

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
    if (fp == NULL){
        printf("One file wouldn't open!\n");
        exit(EXIT_FAILURE);
    }

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}
brushtakopo
  • 1,238
  • 1
  • 3
  • 16
  • 1
    Note that [`getline()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html) is a POSIX function, not part of the Standard C Library. That matters since the code appears to be running on Windows, judging from the file's pathname. Also, there's no need to test `line` before calling `free(line);` — if `line` is still null (unlikely, even if the first input failed because the file was empty), freeing a null pointer is defined behaviour and a no-op. – Jonathan Leffler Jan 09 '23 at 14:49