0

I need to write two variables to a text file with a space in between them, what I want my text file to look like:

log.txt

www.google.com feb17202101
www.yahoo.com feb17202102
www.xyz.com feb17202103

The domain name and dates are stored in two char arrays.

My code

FILE *fp;
      fp = fopen("log.txt", "w+");
      if(fp == NULL)
      {
        printf("Could not open file 31");
        exit(0);
      }

      fprintf(fp,"%s  %s\n",domainName, fileName);

(DomainName and fileName are two separate char arrays) I was hoping this would print both my variables with a space in between them and go onto the next line so when my function needs to write to the text file again, it will be on a fresh line.

Instead my text file looks like

www.google.com
  022321224825

This seems like it should be the easiest part of my program but it's one of those days where I spent all day coding and now my brain feels fried haha. I can't figure out how to format it properly. If someone could help me out, I would appreciate it!

  • That looks as if the newline character were part of `domainname`. That happens when you read a string with `fgets`. [Remove the new-line character](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) after reading `domainname`. – M Oehm Feb 24 '21 at 06:04
  • @MOehm thank you! It works. – Ana Vanderwoodson Feb 24 '21 at 16:03

1 Answers1

2

As pointed out in comment, I think you have a newline character in domainname array itself. When I try to write two simple arrays to a file like this;

char domainNames[3][20] = {"www.google.com", "www.yahoo.com", "www.xyz.com"}; 
char timestamps[3][20] = {"feb17202101", "feb17202102", "feb17202103"};

for (int i = 0; i < 3; i++) {
    fprintf(fp,"%s %s\n",domainNames[i], timestamps[i]);
}

This prints the following output:

c-posts : $ cat log.txt 
www.google.com feb17202101
www.yahoo.com feb17202102
www.xyz.com feb17202103

If you're getting domainname and timestamp from user input using fgets(), a newline character gets added at the end. You might want to trim it:

void trimTrailingNewline(char input[]) {
    input[strcspn(input, "\n")] = 0;    
}

Then you can use it to remove trailing newlines in either before writing to file or after reading as user input:


for (int i = 0; i < 3; i++) {
    trimTrailingNewline(domainNames[i]);
    trimTrailingNewline(timestamps[i]);
    fprintf(fp,"%s %s\n", domainNames[i], timestamps[i]);
}
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40