How to write numbers between 0 and 10

3

I would like to understand how to write to a file, numbers from 0 to 10, from this code:

main(){
    setlocale(LC_ALL,"Portuguese");
    int num[10],i; 
    FILE *arquivo;
    arquivo = fopen("c:\Ling_C\resultado.txt","a");

    if(arquivo==NULL){
        printf("Arquivo texto.txt não pode ser aberto!\n");
        getchar();
    }
    else{
        for (i=0;i<10;i++){
            fwrite(&num[i],sizeof(int),10,arquivo);
        }
    }
    fclose(arquivo);
    getchar();
}
    
asked by anonymous 26.10.2017 / 18:10

2 answers

4

First the bar is reversed in the path of the file.

According to the fopen function, the parameters fopen("file", **a**) indicates that it will concatenate at the end of the file, use the fopen("file", **w**) if you want to overwrite.

For writing to files you can use the function fprintf , follow the link with definition of some functions for writing in files:

The functions fputc (), fprintf () and fputs ()

See the example below and then its output:

#include <stdio.h>
#include <conio.h>

int main(void){
    FILE *arq;
    int result;

    arq = fopen("C:/Users/inpart/Desktop/EstudoC/ArqGrav.txt", "w");  

    if (arq == NULL)
    {
     printf("Arquivo ArqGrav.txt não pode ser aberto!\n");
     return 0;
    }

    for (int i = 0; i<10;i++)
    {
      fprintf(arq,"Linha %d\n", i);                       
    }

    fclose(arq);

    return 0;
}

    
26.10.2017 / 18:28
4

The @CaiqueRomero response attacked the problem on the one hand that I consider unexpected, but very good. He also talks about all the other things about opening files and left great reading references.

I came here to talk about fwrite .

The first thing is to see the function signature:

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

Okay, let's understand what that means. The function says that it will print in stream passed% with% elements of size count pointed to size_t .

If you want to print ten integers of a ptr vector in the v file, you could do:

fwrite(v, sizeof(int), 10, f);

Where:

  • f is the vector, so it can be worked as a pointer
  • v is the size of the vector unit; could also be sizeof(int) or sizeof(*v) , but I'd rather pass the type
  • sizeof(v[0]) is the number of elements
  • 10 is the file open for writing

Some comments:

  • f writes bytes, literally
  • fwrite writes the textual representation
  • It is possible to open the file in binary mode when knowing that fprintf is going to be used, and it usually opens in textual mode to fwrite for performance issues
    • to open for binary reading, fprintf as argument of rb ; write is with fopen
  • If you try to textically open a file filled with wb , you'll get a result like this (credits to @ CaiqueRomero by print):

    
26.10.2017 / 22:44