Ana Vanderwoodson
Ana Vanderwoodson

Reputation: 39

How to write two variables to the same line in .txt file? C lang

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!

Upvotes: 0

Views: 351

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 5882

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]);
}

Upvotes: 2

Related Questions