Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to write the numbers 1-10 to two different files. I guess I should use the for loop to both print to the files and count from 1 to 10 as it loops but I don't know how.

share|improve this question
add comment

2 Answers 2

up vote 6 down vote accepted

Count to 10:

seq 10

Write to two files:

tee file1 >file2

(Without the >, tee writes to the two files and additionally to its standard output, i.e. to the terminal unless redirected.)

Count to 10 and write the output to two files:

seq 10 | tee file1 >file2
share|improve this answer
add comment

To do this with a for loop, you use the loop counter to write the number.

for (i = 1; i <= MAX; ++i)
    fprintf(file1,"%d\n", i);

A complete example in C:

#include <stdio.h>

int main()
{
    FILE *file1, *file2;
    file1 = fopen("file1.txt","w");
    file2 = fopen("file2.txt","w");

    int MAX = 10;

    int i;
    for (i = 1; i <= MAX; ++i)
    {
        fprintf(file1,"%d\n", i);
        fprintf(file2,"%d\n", i);
    }

    fclose(file1);
    fclose(file2);

    return 0;
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.