Can't create or write a .txt file in C - c

I'm trying to create and write to a file in C - for whatever reason this code is running successfully however, doesn't create a file. Please find my code below, any help would be appreciated
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num;
FILE* fptr;
fptr = fopen("E:\\SAMPLE FILES\sample.txt", "w+");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
(void)scanf("%d", &num);
fprintf(fptr, "%d", num);
fclose(fptr);
return 0;
}

This is a very simple problem.
fptr = fopen("E:\\SAMPLE FILES\sample.txt", "w+");
This is the problem. As you would know, the \ is used to define an escape sequence. Because of that, for an actual \, you have to put it 2 times, like you did at E:\\. The file, instead of creating in SAMPLE FILES, is created at the root directory.
Change it to :
fptr = fopen("E:\\SAMPLE FILES\\sample.txt", "w+");
And your code should work. I tested it an I got output.
Make sure you have a folder named SAMPLE FILES on E: Or else, fopen() returns NULL.

In order to open a file for reading or writing, it is best to at least have some sort of error checking and reporting on it. Please see the basic example below:
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main () {
FILE * pf;
int errnum;
pf = fopen ("e:\\sample files\\sample.txt", "wb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
} else {
printf("Enter num: ");
(void)scanf("%d", &num);
fprintf(fptr, "%d", num);
fclose(fptr);
fclose (pf);
}
return 0;
}
At least that way, if you get an error being displayed, you stand a good chance of fixing or dealing with it programmatically.

fptr = fopen("E:\SAMPLE FILES\sample.txt", "w+");
->
fptr = fopen("E:\SAMPLE FILES\sample.txt", "w+");
try

Related

Listing all logged in user and saving it into a text file in C, linux

i would like to know how can i list all the current logged user and save it to a text file and list all files info on the current directory and save it as well using c. i have tried system("w"), system("ls -l") to list the users but it wont save using fprintf and the only output i get is 0 and nothing for ls -l. i'm relatively new into programming and linux. please help.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char opt;
printf("Enter an Option A/B: ");
scanf("%c", &opt);
if (opt == 'A')
{
int list;
time_t tm;
time(&tm);
int i,j;
i = system("w");
j = system("ls -l");
printf("The Date and Time are: %s", ctime (&tm));
printf("\n");
FILE *fptr;
fptr = fopen("file1.txt", "w");
fprintf(fptr, "%s", ctime (&tm));
fprintf(fptr, "%i", i);
fprintf(fptr, "%j", j);
fclose(fptr);
}
else
{
printf("bye");
}
return 0;
}
Try this code with popen(), fgets read the file line at a time. You can replace printf function with anything you like.
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}
code source: https://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html

How to dump txt file in C?

#include <stdio.h>
int main(void) {
int name;
int arrival_time;
int size;
int ret;
FILE * fp = fopen_s("C:\\NIA\\data.txt", "rt");
while (1)
{
ret = fscanf_s(fp, "%d %d %d", &name, &arrival_time, &size);
if (ret == EOF)
break;
printf("%d %d %d \n", name, arrival_time, size);
}
return 0;
}
I want to dump my txt file to project but errors are coming out. I'm confused about memory initiation and file format, variables, etc. How can I fix this and print values well?
My txt file is :
Your question lacks the most important information: What is going wrong.
When I compile your code, I get errors for fopen_s. (OK, this is mainly because I use gcc ;) )
The manual tells us how this function looks like:
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
This means, you must use it like this:
errno_t err;
FILE *fp;
err = fopen_s(&fp, "C:\\NIA\\data.txt", "rt");
if (err != 0)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
Or you stick to standard functions and use them as you already tried:
FILE *fp;
fp = fopen("C:\\NIA\\data.txt", "rt");
if (fp = NULL)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
You should definitely add checks for all return values. At least for I/O related functions like fopen and scanf.
Also closing your file would be adviseable. While it is only opened in read mode, it will not cause much trouble as it is closed automatically on program termination, but it is surely good style to do it.
An improved version could look like this:
(As you do not scan strings, there is no benefit using MS non-standard function scanf_s)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int name;
int arrival_time;
int size;
FILE * fp = fopen("data.txt", "rt");
if (fp == NULL) {
perror("File data.txt cannot be opened");
exit(1);
}
while (fscanf(fp, "%d %d %d", &name, &arrival_time, &size) == 3)
{
printf("%d %d %d\n", name, arrival_time, size);
}
fclose(fp);
return 0;
}
This prints the content of your data.txt file on the console.
If dumping you txt file means closing the txt file after using it, you can use the following
fclose(fp);
before the return 0;

C - Read file line by line

The code is running well, it's just that I feel there are still many mistakes and give me a little direction to improve in the future. I want to learn how to maintain the code properly.
fix the code as it should!
Data.txt
[1] Line numbers 1.
[2] Line numbers 2.
[3] Line numbers 3.
[4] Line numbers 4.
[5] Line numbers 5.
[6] Line numbers 6.
My code:
#include <stdio.h>
#include <stdlib.h>
int getLengthFile(char *namafile)
{
FILE *fptr;
int n =0;
fptr = fopen(namafile, "r");
if(fptr != NULL){
char c;
while((c = getc(fptr)) != EOF) {
++n;
}
fclose(fptr);
}
return n;
}
int main(){
FILE *fptr;
int i;
fptr = fopen("Data.txt","r");
if(fptr != NULL){
printf("Succes reads file!\n");
if(getLengthFile("Data.txt")>0){
char strLine[225];
while(fgets(strLine,225,fptr) != NULL){
printf("%s",strLine);
}
}else{
printf("File is empty!\n");
}
fclose(fptr);
}else{
printf("Error reads file!\n");
}
return 0;
}
Here is a more or less fixed version of the code presented in the first edition of the question, where the getLengthFile() function was not present. In my opinion, that function does not provide useful functionality. If you must report that the file contained no data, you could do so by counting the number of times fgets() returns any data — if it returns any data, the file was not empty.
#include <stdio.h>
int main(void)
{
const char filename[] = "Data.txt";
FILE *fptr = fopen(filename, "r");
if (fptr == NULL)
{
fprintf(stderr, "Error opening file %s for reading!\n", filename);
return 1;
}
printf("Success opening file %s for reading\n", filename);
char strLine[225];
while (fgets(strLine, sizeof(strLine), fptr) != NULL)
printf("%s", strLine);
fclose(fptr);
return 0;
}
When there is no file Data.txt, example output is:
Error opening file Data.txt for reading!
When there's a file containing one short line of data, example output is:
Success opening file Data.txt for reading
data from the file Data.txt
I also tested it on a file with longer lines, including lines with as many as 380 characters, and the output from the program was the same as the input except for the line saying 'Success opening file Data.txt for reading'.

Avoid code duplication in read/write functions using preprocessor

If I have a pair of long functions:
#include <stdio.h>
#include <stdlib.h>
void writeData()
{
FILE *fp; int someVar1 = 1; int someVar2 = 2; int someVar3 = 3;
fp = fopen("results.dat", "a"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
fprintf(fp, "%d\n", someVar1); // write to file
fprintf(fp, "%d\n", someVar2); // write to file
fprintf(fp, "%d\n", someVar3); // write to file
fclose(fp); // and close
}
void readData()
{
FILE *fp; int someVar1, someVar2, someVar3;
fp = fopen("results.dat", "r"); // open file for reading
if (fp == NULL) {
printf("I couldn't open results.dat for reading.\n");
exit(0);
}
fscanf(fp, "%d\n", &someVar1); // read from file
fscanf(fp, "%d\n", &someVar2); // read from file
fscanf(fp, "%d\n", &someVar3); // read from file
fclose(fp); // and close
printf("someVar: %d %d %d\n", someVar1, someVar2, someVar3);
}
int main(void)
{
writeData();
readData();
return 0;
}
Is there a way I can (ab)use the preprocessor to avoid duplicating read and write code? In other words, is there a way to generate pairs of fprintf(fp, "%d\n", someVar) and fprintf(fp, "%d\n", someVar) in the write() and read() functions respectively?
EDIT: this could equally apply to allocating/deallocating a whole load of memory, e.g. http://pastebin.com/wdAnHfWx. Basically any task which has a lot of code repetition between two complementary, but simple functions.
There is a technique known as X Macros that may fit to your needs. You can check a basic information of how it works in wikipedia (http://en.wikipedia.org/wiki/X_Macro).
Following the wiki explanation, you could create a VAR_LIST, and later expand this list as read or write.
#define MY_VAR_LIST(ENTRY) \
ENTRY(var1) \
ENTRY(var2) \
ENTRY(var3)
#define EXPAND_AS_DEFINITION(my_var) int my_var;
#define EXPAND_AS_WRITE(my_var) fprintf(fp, "%d\n", (my_var));
#define EXPAND_AS_READ(my_var) fscanf(fp, "%d\n", &(my_var));
int my_function_write()
{
MY_VAR_LIST(EXPAND_AS_DEFINITION)
FILE *fp;
fp = fopen("results.dat", "a"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
MY_VAR_LIST(EXPAND_AS_WRITE)
fclose(fp);
}
int my_function_read()
{
MY_VAR_LIST(EXPAND_AS_DEFINITION)
FILE *fp;
fp = fopen("results.dat", "r"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
MY_VAR_LIST(EXPAND_AS_READ)
fclose(fp);
}
So to append a new var, you just need to update your VAR_LIST.
I did not tried to compile my code, so there is probably some syntax error, but that is the way it should work.
Why preprocessor? You can to that right in code, something like this
#define READ 0
#define WRITE 1
void do_some_io( int action )
{
FILE *fp; int someVar = 1;
fp = fopen("results.dat", (action == WRITE ? "a" : "r") ); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for io.\n");
exit(0);
}
if ( action == WRITE )
fprintf(fp, "%d\n", someVar); // write to file
else
fscanf(fp, "%d\n", &someVar); // read from file
fclose(fp); // and close
}
Looking at your code, I'd say it's not worth the effort, because there are too many differences in it ("a" vs. "r" in open, different error messages, printf vs. scanf, extra printf). The whole thing will be messy to create and even more messy to undestand if someone will have to read or debug it a year later.
However, for educational purposes:
#define MYFUNC(NAME,VARPART1,VARPART2) \
void NAME () { \
int a= 0; \
VARPART1; \
VARPART2; \
}
// make a print function
MYFUNC(printit, printf("%d", a), return);
// make a scan function:
MYFUNC(scanit, scanf("%d", &a), *global= a);
will create two different functions with one macro, e.g the first will be:
void printit () {
int a= 0; \
printf("%d", a);
return;
}

fprintf not working C

I'm trying to make a simple program that writes to a .txt file, but this code won't work.
#include <stdio.h>
#include <string.h>
#include "main.h"
int main(int argc, const char * argv[])
{
FILE *f = fopen("text.txt", "w+");
char c[256];
printf("What's your name?\n");
scanf("%s", c);
fflush(f);
if (c!=NULL)
{
printf("not null\n");
int q = fprintf(f, "%s", c);
printf("%d", q);
}
else
{
printf("null\n");
}
printf("Hello, %s\n", c);
fclose(f);
return 0;
}
The printf returns that it's not null, and the int q returns whatever the length of the char is. Why isn't this writing to the file?
the printf returns that it's not null,
Thats because c is not null , since you have scanned your name string into it.
Why isn't this writing to the file?
The program is working fine , on my system.
-- Edit --
FILE *f = fopen("text.txt", "w+");
if (NULL == f)
perror("error opening file\n");
By doing the error handling this way , the exact reason (in your case permissions) , would be displayed,
Turns out I wasn't running with the correct permissions. Stupid mistake on my part.
First off, you've declared c in local scope, so it will never be NULL. If you want to check whether or not the user entered anything, check the length of c after you've scanned in the string:
if (strlen(c) == 0) {
///
}
Second, check whether or not you have permission to write to the current working directory. You should be checking the return value of fopen:
if (!f) {
fprintf(stderr, "Failed to open text.txt for writing\n");
}

Resources