print to a file

0 raphael mhandu · April 11, 2015
Que ; Write a program that reads a number, then prints the integers from 1 to the number to a file.

Post a Reply


Oldest  Newest  Rating
0 Fayazur Rahman Summit · April 11, 2015
its a simple coading

somthing like this

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

int main()
    int i=0, j;
    printf("Write an integer number: ");
    scanf("%d", &j);

        printf("%d \n",i++);

    return 0;
0 Clark Alaan · April 12, 2015
Hello, I believe what you are trying to do is actually work with files such as *.txts and therefore I will answer your question as such.

You need to use a FILE type variable, which is already part of stdio.h so if you have included that already then all is good. Note that this is a pointer-type variable(not exactly sure if this is the term), so we use a pointer as a name like so:
FILE *fp;

Next thing we need to initialize our fp. For this, we need to use fopen("PathName\File.extension", "w"); the second argument, "w" tells the function that we are going to write to this file.
fp = fopen("FileName.txt", "w");

Now we can write to the file.
We use fprintf(FILE,"String",args); to write to a file. After passing the FILE variable as a first argument, we can pretty much use it as we use the standard function printf();

int x = 5;
fprintf(fp, "This is a string: and here's and int: %d", x);

As a standard(and good) practice to avoid memory leakage(or something to do with memory), we should close the opened file with:


So your code would somewhat look like this:


int main(){
int a,i=1;
FILE *fp;
fp = fopen("FileName.txt", "w");

printf("Enter an integer: ");
scanf("%d", &a);

  fprintf("%d ",i);
return 0;

Hope this helps! :D

Edit: The formatting messed up for some reason.
Edit2: Thanks c student. I thought there wasn't any particular meaning to the int return value on the main function(kinda had an idea just didn't really want to think about it). I edited it to also include the increment. XD
0 c student · April 12, 2015
@Clark Alaan
Also remembering to increment the i variable each loop.

And a side note on declaring main:
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator