1

The task is write a c program to print lines read from an input file (maybe very very large), but without '\n'. Please see the comment in the code below, is it a typical way or good way to do so??

int main() {
const char *input_wavlist_file = "/home/legend0011/Downloads/test-sample-list.txt";

const int BUFFER_SIZE = 100;

FILE *fr = fopen(input_wavlist_file, "r");

if (fr == NULL) {
    printf("Error opening input wav list file!\n");
    exit(1);
}

char str[BUFFER_SIZE];
while((fgets(str, BUFFER_SIZE, fr)) != NULL) {
    char *pch = strchr(str, '\n');

    char *filepath = str;
    if (pch != NULL) *pch = '\0';  // is this a typical way????????
    printf("reading==>%s",filepath);
}

fclose(fr);

}

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
legend0011
  • 139
  • 7

3 Answers3

1

The issue you're facing here is with fgets() behaviour. As per the man page,

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....

So, it reads and stores the tralining newline into the read buffer. That is the one which is getting printed to the output. Instead of trying n_not to print_ the newline, you can simply replace the trailing \n with \0 after taking the input to get your issue solved.

As this is a simple replacement operation, without having strchr() also you can get the job done in an easy way.

Simple Algo:

  1. Read the line using fgets().
  2. If the return is not NULL, calculate the length of the input using strlen().
  3. Replace the buffer[strlen-1] element (actually \n, you can double-check) with null \0.

note: The proper signature of main() is int main(void)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

fgets() comes with a newline character suppress the newline and print it.

size_t n = strlen(str);

if(n>0 && str[n-1] == '\n')
{
  str[n-1] = '\0';
}

printf("%s",str);
Gopi
  • 19,784
  • 4
  • 24
  • 36
0

This answers the question in your comment. There is no string assign operator in c. You have to provide some space for this new string or destructively ammendment the original.

The simplest way to achieve what you want would be use strncpy to copy the first n characters of your source string to a new destination.

phil
  • 561
  • 3
  • 10