How to write numbers between 0 and 10 to a file

Asked

Viewed 503 times

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

2 answers

4


First bar is reversed in the file path.

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

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

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

See the example below and then your 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;
}

inserir a descrição da imagem aqui

  • I expected an answer with fwrite, in this certainly worth my +1

  • Me too , but it sure was worth my +1

4

To reply from @Caiqueromero attacked the problem in a way that I consider unexpected, but very good. He also talks about the other things related to 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 this means. The function says it will print on stream past tense count elements of size size_tpointed out by ptr.

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

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

Where:

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

Some remarks:

  • fwrite writes the bytes, literally
  • fprintf writes the textual representation
  • It is appropriate to open the file in binary mode when knowing that the fwrite, and normally opens in textual mode to fprintf for performance reasons
    • to open for binary reading, rb as an argument from fopen; writing is with wb
  • if you try to open a textual file filled with fwrite, you will get a result like this (credits to @Caiqueromero by print):

print do @CaiqueRomero tentando abrir um arquivo binário com um editor de texto: apenas caracteres incompreensíveis

  • Very good face answer!

  • Well explanatory , increases more my knowledge , worth !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.