When writing to a file, fputs() does not change line - c

I'm currently trying to create a database in C, using a .txt document as the place to store all the data. But I can't get fputs() to shift line, so everything that my program writes in this .txt document is only on one line.
int main(void){
char c[1000];
FILE *fptr;
if ((fptr=fopen("data.txt","r"))==NULL){
printf("Did not find file, creating new\n");
fptr = fopen("data.txt", "wb");
fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
fputs("//Feel free to edit the file as you please.",fptr);
fputs("'\n'",fptr);
fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",fptr);
fputs("sum = 2000 //how much money there is, feel free to edit this number as you please.",fptr);
fclose(fptr);
}
fscanf(fptr,"%[^\n]",c);
printf("Data from file:\n%s",c);
fclose(fptr);
return 0;
}
This is my testing document.
I feel like I've tried everything and then some, but can't get it to change line, help is much appreciated.
Btw. The output looks like this:

There are two issues in your program :
You should specify "w" rather than "wb" so that the file is read and written as text rather than binary. Although in some systems this makes no difference and b is ignored.
The part for file reading should be in an else, otherwise it executes after file creation with fptr not containing a valid value.
This is the code with those corrections. I do get a multiline data.txt with it.
int main(void){
char c[1000];
FILE *fptr;
if ((fptr=fopen("data.txt","r"))==NULL){
printf("Did not find file, creating new\n");
fptr = fopen("data.txt", "w");
fputs("//This text file contain information regarding the program 'mon
fputs("//This text file contain information regarding the program 'mon
fputs("//Feel free to edit the file as you please.",fptr);
fputs("'\n'",fptr);
fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",
fputs("sum = 2000 //how much money there is, feel free to edit this nu
fclose(fptr);
}
else
{
fscanf(fptr,"%[^\n]",c);
printf("Data from file:\n%s",c);
fclose(fptr);
}
return 0;
}

Related

Can't manage to open a file stream in C

I had to write a simple database (console application) in C: You could input gender, name and adress of people and the data would be saved in an array of structs called 'Person'. You could then also display all entries or delete entries again. So far so good.
Now I have to add functions to save the data into a .csv file and read from it again. However, the function fopen() always returns a NULL-pointer, so I can't even get to the reading or writing part. Below is my code. I hope you can tell me why not even this first step is working. I'm rapidly losing any confidence I had in my C abilities.
void save(Person persons[]) {
char name[LEN];
printf("File Name: ");
fgets(name, LEN, stdin);
fflush(stdin);
name[strlen(name)] = '\0';
FILE *file = fopen(name, "wx");
if (!file) {
printf("The file couldn't be created.\n\n");
}
}
why not even this first step is working.
fopen(name, "wx") certainly returns NULL as name contains '\n'. Improbable that such a file name exists.
See Removing trailing newline character from fgets() input.

Why do I have NUL line in my written file using fopen fclose c++ linux?

I have some C code running on a linux OS into a portable device. I'm using a VRmagic system, similar to BeagleBone etc...).
In this code, I'm using the following function to write results inside a txt file.
//globale definition
FILE *logfile;
const char *logpath = "/MY_DEVICE/log.txt";
const char *main_folder_result_path = "/MEASUREMENT_RESULTS/";
const char *all_measurement_results_file_name = "all_computation_data.txt";
void save_to_log_file(const char *logpath,const char *message){
#ifdef savealllog
logfile = fopen(logpath,"a"); //logpath = "/MY_DEVICE/log.txt";
fprintf(logfile,"%s",message);
fclose(logfile);
#endif
#ifdef printalloutput
printf("%s",message);
#endif
}
void append_all_measurement_file(){
char buff[255];
char filename[255];
save_to_log_file(logpath," Appending all measurement file...");
sprintf(filename,"%s%s",main_folder_result_path,all_measurement_results_file_name);
//here after we create the header if the file does not exist already
FILE *pFile_all_measurement_results = fopen(filename, "r"); //lets try to read the file
if (pFile_all_measurement_results == NULL){ // if file does not exist
pFile_all_measurement_results = fopen(filename, "w");
fprintf(pFile_all_measurement_results,"date-time S_type Part_name batch count abs value_1 value_2 value_3 value_4\n");
fclose(pFile_all_measurement_results);
}
else{
fclose(pFile_all_measurement_results); //if file does exist then we have to close it here
}
//here after we are going to write results
pFile_all_measurement_results = fopen(filename, "a"); //lets open the file in append mode
fprintf(pFile_all_measurement_results,"%s %s %s %d %d %d ",dateandtimetps.dt,measurement_type_str,Name_Str, batch_number,count_number,absolute_measurement_number);
fprintf(pFile_all_measurement_results,"%.03f ", value_1);
fprintf(pFile_all_measurement_results,"%.03f ", value_2);
fprintf(pFile_all_measurement_results,"%.03f ", value_3);
fprintf(pFile_all_measurement_results,"%.03f\n", value_4); //(there are a bit more in reality.....)
fclose(pFile_all_measurement_results); //we can now close the file
save_to_log_file(logpath,"done.\n");
}
99.9% of the time all is OK.
But, randomly, I do have some NUL character in my file, and this happen when I turn OFF my system.
Looks like the file has not been closed properly or something like that for some reason.....
When I get my txt file, and open it with notepad++ on my computer, it does look like the following:
I can confirm that the device has been turned OFF between line 172 and line 174.
Many thanks for help
Just closing a file on Unix systems does not implicate the contents are instantly written to disk; usually buffering/caching is enabled.
To make sure the contents are written you can use sync() immediately after a write and/or close operation, which will minimize the risk of lost updates.
Additionally I recommend to use a journaling filesystem like ext4 (which may not be an option on external drives like USB pens, but is strongly recommend for all system and data partitions). This will not save you from data loss in case of a power failure or crash, but will avoid inconsistencies/partial writes like you are experiencing.

fgets() not working.in C?

Edit: Deleted all but the main question.
My program here is supposed to create a file at a specified directory, and write specified text to it. A correct file's path and content should look something like this:
Path: D:\test.txt
Content: The printing succeeded.
For some reason, my code won't recognize the "path" variable. I don't know what I'm doing wrong here. The "text" variable works fine.
#include<stdio.h>
int main()
{
//Declaring variables
char path[999];
char text[999];
FILE *fp;
//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);
//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);
//opening and printing to file.
//fp = fopen("D:\\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);
//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}
The thing I don't understand is that fp = fopen("D:\\test.txt", "w"); works, but fp = fopen(path, "w"); doesn't. I've tried putting in these different paths.:
D:\\test.txt
D:\test.txt
D\test.txt
D\\test.txt
It doesn't open the file when you open the variable path because fgets() reads the newline and puts it at the end of the string (if there's enough space in the buffer). In order to make it work you have to manually remove the newline from the string.
Try this before opening the file.
if(isspace(path[strlen(path)-1]))
path[strlen(path)-1]='\0';
You might also need to include <ctype.h>

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 (\)?

Trouble testing copy file function in C

Okay so this is probably has an easy solution, but after a bit of searching and testing I remain confused.. :(
Here is a snippet of the code that I have written:
int main(int argc, char *argv[]){
int test;
test = copyTheFile("test.txt", "testdir");
if(test == 1)
printf("something went wrong");
if(test == 0)
printf("copydone");
return 0;
}
int copyTheFile(char *sourcePath, char *destinationPath){
FILE *fin = fopen(sourcePath, "r");
FILE *fout = fopen(destinationPath, "w");
if(fin != NULL && fout != NULL){
char buffer[10000];//change to real size using stat()
size_t read, write;
while((read = fread(buffer, 1, sizeof(buffer), fin)) > 0){
write = fwrite(buffer, 1, read, fout);
if(write != read)
return 1;
}//end of while
}// end of if
else{
printf("Something wrong getting the file\n");
return 0;}
if(fin != NULL)
fclose(fin);
if(fout != NULL)
fclose(fout);
return 0;
}
Some quick notes: I am very new to C, programming, and especially file I/O. I looked up the man pages of fopen, fread, and fwrite. After looking at some example code I came up with this. I was trying to just copy a simple text file, and then place it in the destination folder specified by destinationPath.
The folder I want to place the text file into is called testdir, and the file I want to copy is called test.txt.
The arguments I have attempted to use in the copyFile function are:
"test.txt" "testdir"
".../Desktop/project/test.txt" ".../Desktop/project/testdir"
"/Desktop/project/test.txt" "/Desktop/project/testdir"
I just get the print statement "Something wrong getting the file" with every attempt. I am thinking that it may be because 'testdir' is a folder not a file, but then how would I copy to a folder?
Sorry if this a really basic question, I am just having trouble so any advice would be awesome!
Also, if you wanted to be extra helpful, the "copyTheFile" function is supposed to copy the file regardless of format. So like if its a .jpg or something it should copy it. Let me know if any of you guys see a problem with it.
This is with ISO/POSIX/C89/C99 on Linux.
At the start, you'll want to include stdio.h to provide FILE and the I/O function declarations:
#include <stdio.h>
Aside from this, your program compiles and works properly for me. Unfortunately you can't copy to a directory without using stat() to detect if the destination is a directory, and if so, appending a file name before opening the file.
Some other minor suggestions:
A buffer with a power of two bytes such as 4096 is probably more efficient due to it lining up with filesystem and disk access patterns
Conventionally, C functions that return a status code use 0 for success and other values such as 1 for failure, so swapping your return values may be less confusing
When a standard library function such as fopen, fread or fwrite fails, it is a good idea to use perror(NULL); or perror("error prefix"); to report it, which may look something like:
$ ./a.out
...
error prefix: No such file or directory
if you are trying to write a new file in a directory, you should be giving the full path of the file to be written. in your case
"C:...\Desktop\project\testdir\testfile"

Resources