BUENO
BUENO

Reputation: 9

Can not open files with c

Im supposed to write a program that opens an excel file, reads the numbers on the file, multiplies them by 9.8 and the shows the answer in another excel gile.

I wrote this, and I did not get any errors in the compiler, but when I run it, it does not open any files. How do I make it open the files?

#include <stdio.h>

int main() {
    FILE *archivo;
    FILE *archivoSalida;

    int masa;
    float peso;

    archivo = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoEntrada.txt", "r");
    archivoSalida = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoSalida.txt", "r");

    if (archivo != NULL) 
    {  
        printf("The file was opened succesully");

        while (fscanf(archivo,"%d", &masa)!= EOF)
        {
            peso=masa*9.81;
            fprintf(archivoSalida, "%f\n", peso);
        }
    }
    else
    {
        printf ("Error");
    }


    fclose(archivo);
    fclose(archivoSalida);

    return 0;
}

Upvotes: 0

Views: 71

Answers (3)

Duane McCully
Duane McCully

Reputation: 406

The file names look Windows-ish. Is it possible that all of the forward slashes (/) that you have in both file names should really be back slashes (\)?

Upvotes: 0

JimmyB
JimmyB

Reputation: 12610

  1. You'll want to fopen the output file ("archivoSalida") with mode "w" (for write) instead of "r" (for read). See e.g. http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html.

  2. You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?

  3. Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.

Upvotes: 2

dkg
dkg

Reputation: 1775

Your file denominated by archivoSalida is opened in read mode ('r').

You should also check the return codes of read/writes functions to be sure everything happen as wanted.

Upvotes: 1

Related Questions