how to use fprintf in terminal (Mac OS) - c

I'm using esc ANSI code, ao I need to run my program via terminal. when I'm trying to use fprintf and executing the program from the console, nothing is saved in the text file. Running the program from Xcode directly, it does save the text in the file.
int main()
{
int write;
FILE *file;
file = fopen("frucht.txt", "w+");
gotoxy(4, 10);
scanf("%d", &write);
fprintf(file,"%d", write);
fclose(file);
return(0);
}

Related

C program not writing to a file

I was reading "C: How to program" on chapter 11 (File handling) and came with this algorithm, to append a string to a file named info.txt but it isn't working at all. What am I doing wrong?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
FILE *fp = fopen("info.txt","w");
char buff[100];
if(fp == NULL){
fprintf(stdout,"Error opening file\n");
exit(1);
}
while(!feof(stdin)){
fprintf(stdout,"Type a string/\nEOF ends input\n");
if(!fgets(buff,sizeof buff,stdin)){
fprintf(stderr,"Error reading string");
exit(2);
}
buff[strcspn(buff,"\n")] = 0;
fprintf(fp,"%s",buff);
}
fclose(fp);
}
I guess you are inserting EOF wrongly. As it is answered here, EOF is inserted using CTRL+D in Unix systems and using CTRL+Z in Windows.
Using exactly your code it works for me, so I guess you are trying to insert EOF using CTRL+C, or another command, which closes the application and leaves the file empty.
Also, if you want it to append always, even if you close the program and open it again, you should use the mode append "a" instead of write "w" [reference]
FILE *fp = fopen("info.txt","a");

C fopen creating file in my user directory instead of desktop Mac

I am messing around with reading and writing to files in C. I coded a program, which is saved on my desktop. I then compiled it using the terminal, also on the desktop. But when I ran the program, it said that everything was working, but the file was nowhere to be found. I used the spotlight search, and it said that my file was located in my /Users/johndoe directory. Here is the code. Thanks in advance for helping.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE* fp1 = fopen("boop.txt", "a");
fputs("Hello World\n", fp1);
fclose(fp1);
FILE* fp2 = fopen("boop.txt", "r");
char* output = (char *) malloc(20);
fgets(output, 20, fp2);
printf("%s", output);
fflush(stdout);
return 0;
}
What do you mean when you say the terminal is "also on the desktop"? I suspect you mean that the icon the execute the terminal is on the desktop, but the shell that is running inside the terminal has a working directory of $HOME. When you run the program from the shell, type pwd to see the directory it is running in. That is the directory in which the files will be created.

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;
}
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.
You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?
Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.
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.
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 (\)?

Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C?

Why does fprintf give different results in the following example programs?
Example 1:
int main(){
FILE *f;
char buf[512];
char name[128] = {"filename"};
f = fopen(name, "w");
fprintf(f, "asdas\n");
fprintf(f, "asdas\n");
while(1){}
return 0;
}
If I terminate this program using CTRL+C, I get an empty file named filename.
However, using
Example 2:
int main(){
FILE *f;
char buf[512];
char name[128] = {"wpa_supplicant.conf"};
f = fopen(name,"w");
while(1){
fprintf(f, "asdas\n");
}
return 0;
}
If I terminate this program using CTRL+C, I get file named filename, and it contains many lines with the string asdas.
Why are the strings not written to the file in the first example, but they are written to the file in the second example?
In the second case, there are enough fprintf calls for the internal buffers to be flushed to disk.
With the first program, if you put a fflush(f) before the while loop, the strings will be written to the file.
#include <stdio.h>
int main(void) {
FILE *f = fopen("filename", "w");
if (!f) {
perror("Failed to open 'filename' for writing");
exit(EXIT_FAILURE);
}
fprintf(f, "asdas\n");
fprintf(f, "asdas\n");
if ( fflush(f) != 0 ) {
perror("Flushing output failed");
exit(EXIT_FAILURE);
}
while(1){}
return 0;
}
Output:
C:\...\Temp> cl file.c
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x64
...
/out:file.exe
C:\...\Temp> file
^C
C:\...\Temp> type filename
asdas
asdas
Keep in mind:
Upon successful completion, fflush() shall return 0; otherwise, it shall set the error indicator for the stream, return EOF, and set errno to indicate the error.
As mentioned in the answer by #SinanÜnür this is indeed an issue with the buffering of data in internal buffers. You need to flush manually in the first case to get that data actually written into the file.
However, FWIW, I just want to add here, you see this behavior because of the abnormal termination of the program by a signal (generated by CTRL+C).
If your program would have ended normally, (for example, by calling exit(), after a large-enough but controlled while() loop), then both the cases would have shown the same behavior, as in that scenario, all the open streams would have been flushed automatically.
The exit() function shall then flush all open streams with unwritten buffered data and close all open streams. Finally, the process shall be terminated ...

Autostart application in Linux, output fail

friends. I am using Debian Linux (Raspberry Pi), I want to autostart a program after linux startup.
It's a C program, it can printf on Terminal and fprintf on a text file, I have compiled it and got exe file(file name is test) Path is /home/username/try/test ,the program can run successfully, printf and fprintf can work. After I got exe file, I run command
sudo chmod +x /home/usernane/try/test
Then I create a new folder "autostart" in /home/username/.config Then I run command
cd /home/username/.config/autostart
sudo nano test.desktop
I continue to write desktop file:
[Desktop Entry]
Name=test
exec=lxterminal -e "/home/username/try/test"
Type=Application
After this, I reboot. the program can autostart, but when the program start to fprintf, the program quit. I delete fprintf in code, redo everything, Program can run successful and can printf results.
so problem is fprintf(I want to output results to a txt file)! I tried many ways and can't solved. I need your suggestions, thanks!
I did fprintf as the following: (I run the program normally (Not Autostart), it can work.If autostart, program will quit)
FILE *fp;
char results[50]
/* check if file could be opened */
if((fp=fopen("xy.txt", "w")) == NULL) { // or use "a" instead of "w" to create the file if it doesn't exist
printf("Cannot open file.\n");
exit(1);
}
/* put your results into results[] */
....
/* afterwards writing to file */
fprintf(fp, "%s", results);
fclose(fp);
Have you tried to do it like this?:
FILE *fp;
char results[50]
/* check if file could be opened */
if((fp=fopen("test.txt", "w")) == NULL) { // or use "a" instead of "w" to create the file if it doesn't exist
printf("Cannot open file.\n");
exit(1);
}
/* put your results into results[] */
....
/* afterwards writing to file */
fprintf(fp, "%s", results);
fclose(fp);

Resources