Unable to save a char array using fprintf() - arrays

I am unable to save a char array using fprint() and i cannot figure out why. The below codes compliles correctly but saves nothing to file. Please advise.
static char bitSpecial[100];
int main(int argc, char *argv[]) {
FILE *fp
fp = fopen(thefilename, "w+");
if (fp == NULL) {
printf("I couldn't open file for writing.\n");
exit(0);
}
/* populate bitSpecial one character at the time and verify array is full */
fprintf(fp,"%s", bitSpecial);
if (fclose(fp) != 0) puts("Unable to close the file");
return
}

It'll be easier to identify the problem with the full code. I tried the following snippet and it worked:
#include <stdio.h>
#include <string.h> // for strerror
#include <errno.h> // for errno
static char bitSpecial[100];
int main(int argc, char *argv[])
{
char * thefilename = "test";
FILE *fp;
fp = fopen(thefilename, "w+");
if (fp == NULL) {
printf("I couldn't open file for writing.\n");
return 1;
}
/* populate bitSpecial one character at the time and verify array is full */
bitSpecial[0] = 'a';
bitSpecial[1] = '\n';
bitSpecial[2] = '\0'; // terminator
if (fprintf(fp,"%s", bitSpecial) < 0)
printf("[+] fprintf failed with '%s'\n", strerror(errno));
if (fclose(fp) != 0)
puts("Unable to close the file");
return 0;
}
Verify that you put a null terminator (\0) at the end of bitSpecial, and check the return value of fprintf.

Related

Unable to read from file from argv

I am trying to read from a file, and here is my code, but as I run my code nothing shows up. Have I used the getline() function incorrectly? I can not understand my problem.
const char *READ = "r";
/**
* main - Entry point of my program
*
* Return: On success, it returns 0. On
* error it returns -1
*/
int main(int ac, char **av)
{
FILE *fpointer;
char *lineptr = NULL;
size_t *n = 0;
int line_number = 1;
if (ac != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fpointer = fopen(av[1], READ);
if (fpointer == NULL)
{
fprintf(stderr, "Error: Can't open file %s\n", av[1]);
exit(EXIT_FAILURE);
}
while (getline(&lineptr, n, fpointer) != -1)
{
printf("Line %d: %s\n", line_number, lineptr);
line_number++;
}
return (0);
}
getline(&lineptr, n, fpointer) returns -1. You did not explicitly check this and print an error message.
Checking errno it's because of EINVAL: invalid argument. Also good to check errno.
Reason is that n is NULL, while a pointer to an existing size_t is required.
BTW, indenting with 8 spaces is rather uncommon; I'd stay with 4 space. (Also, never use TAB characters.)
It's advisable to stick with extremely common argc and argv.
Nice you put {s on a further empty line; I like that style.
You'd get this:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
const char *READ = "r";
int main(int argc, char **argv)
{
FILE *fpointer;
char *lineptr = NULL;
size_t n;
int line_number = 1;
if (argc != 2)
{
fprintf(stderr, "USAGE: monty file\n");
exit(EXIT_FAILURE);
}
fpointer = fopen(argv[1], READ);
if (fpointer == NULL)
{
fprintf(stderr, "Error: Can't open file '%s'.\n", argv[1]);
exit(EXIT_FAILURE);
}
if (getline(&lineptr, &n, fpointer) == -1)
{
printf("Failed to read file '%s': %s.\n", argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
do
{
printf("Line %4d: %s\n", line_number, lineptr);
line_number++;
}
while (getline(&lineptr, &n, fpointer) != -1);
return (0);
}
Declaration of getline:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
As an output parameter, the type of n is size_t *. It points to a space for writing by getline.
But in your code, n points to 0, which is NOT a vaild addr to write in.

Using popen to read and write in C using two executables

I understand that popen doesn't allow simultaneous read and write.
To get around this, I created two files, 1.c for writing, and 2.c for reading. The files are included below.
When I run 1.out, I get the expected output on stdout:
bodhi#bodhipc:~/Downloads$ ./1.out
Stockfish 11 64 BMI2 by T. Romstad, M. Costalba, J. Kiiski, G. Linscott
bodhi#bodhipc:~/Downloads$
However, 2.out doesn't give any output on stdout:
bodhi#bodhipc:~/Downloads$ ./2.out
bodhi#bodhipc:~/Downloads$
Where am I going wrong?
1.c:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for writing. */
fp = popen("./stockfish", "w");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
fprintf(fp,"uci\n");
/* close */
pclose(fp);
return 0;
}
2.c:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("./1.out", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it.*/
while (fgets(path, sizeof(path), stdout) != NULL) {
printf("%s", path);
printf("Done!\n");
}
/* close */
pclose(fp);
return 0;
}
while (fgets(path, sizeof(path), stdout) != NULL) {
you don't want to read from stdout, instead:
while (fgets(path, sizeof(path), fp) != NULL) {

Why is fopen not working?

I can't figure out why this isn't working.
#include <stdio.h>
int main(void) {
FILE *in, *out;
// char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ ";
// char *mode = "r";
// in = fopen(FULLPATH, mode);
//
// if (in == NULL) {
// perror("Can't open in file for some reason\n");
// exit (1);
// }
out = fopen("C:\\Users\\Jay\\c\\workspace\\I-OFiles\\out.txt", "w");
if (out == NULL) {
perror("Can't open output file for some reason \n");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
if I remove the // from the commented lines, the error compiler gives is
: Invalid argument
I don't understand why (I read all the other threads related, and nothing).
It does actually write the out.txt file OK, so it doesn't seem like a path misspelled problem.
Remove backslash after in.txt.
The input file name seems bogus:
"C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ "
The filename is just a single space " " and in.txt is probably not a directory.
Change the code to:
const char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt";
Or preferably:
const char *FULLPATH = "C:/Users/Jay/c/workspace/I-OFiles/in.txt";
for better portability as forward slashes work in Windows as well as in Unix.
Furthermore, it is easy to provide more information as to why fopen() failed to open the files.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *in, *out;
in = fopen("C:/Users/Jay/c/workspace/I-OFiles/in.txt", "r");
if (in == NULL) {
perror("Cannot open input file");
exit(1);
}
out = fopen("C:/Users/Jay/c/workspace/I-OFiles/out.txt", "w");
if (out == NULL) {
fclose(in);
perror("Cannot open output file");
exit(1);
}
fprintf(out, "foo U");
fclose(in);
fclose(out);
return 0;
}
Change backslash to slash.
Maybe you don't have permissions or something like that.
out = fopen("C://Users//Jay//c//workspace//I-OFiles//out.txt", "w");
if (!out)
perror("fopen");
return 0;

I am trying to print a txt file and it doesn't work in C homework

I'm writing code that's supposed to verify that a .txt file is a certain format.
I wrote my code as I saw in a tutorial and in the website
and for some reason my program doesn't even print my file.
Can you tell me what I'm doing wrong?
The code will do something far more complex, but I'm still trying to work on my basics.
Here's my code so far:
int main(int argc, char *argv[]) {
/* argv[0] = name of my running file
* argv[1] = the first file that i receive
*/
define MAXBUFLEN 4096
char source[MAXBUFLEN + 1];
int badReturnValue = 1;
char *error = "Error! trying to open the file ";
if (argc != 2) {
printf("please supply a file \n");
return badReturnValue;
}
char *fileName = argv[1];
FILE *fp = fopen(argv[1], "r"); /* "r" = open for reading */
if (fp != NULL) {
size_t newLen = fread(&source, sizeof(char), MAXBUFLEN, fp);
if (ferror(fp) != 0) {
printf("%s %s", error, fileName);
return badReturnValue;
}
int symbol;
while ((symbol = getc(fp)) != EOF) {
putchar(symbol);
}
printf("finish");
fclose(fp);
}
else {
printf("%s %s", error, fileName);
return badReturnValue;
}
}
I think you need a bit more explanations:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
// there might be a macro BUFLEN defined in stdio
// which size is optimized for reading in chunks.
// Test if avaiable otherwise define it
#ifndef BUFLEN
# define BUFLEN 4096
#endif
int main(int argc, char *argv[])
{
char source[BUFLEN];
char *filename;
FILE *fp;
size_t fpread, written;
char c;
int ret_fclose;
if (argc != 2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
// reset errno, just in case
errno = 0;
// work on copy
filename = malloc(strlen(argv[1]) + 1);
if (filename == NULL) {
fprintf(stderr, "Allocating %zu bytes failed\n", strlen(argv[1]) + 1);
exit(EXIT_FAILURE);
}
filename = strcpy(filename, argv[1]);
// try to open the file at 'filename'
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Opening file \"%s\" filename failed\n", filename);
// errno might got set to something usable, check and print
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
}
exit(EXIT_FAILURE);
}
// You have two options here. One is to read in chunks of MAXBUFLEN
while ((fpread = fread(&source, 1, BUFLEN, fp)) > 0) {
// Do something with the stuff we read into "source"
// we do nothing with it here, we just write to stdout
written = fwrite(&source, 1, fpread, stdout);
// you can use 'written' for error check when writing to an actual file
// but it is unlikely (but not impossible!) with stdout
// test if we wrote what we read
if ((fpread - written) != 0) {
fprintf(stderr, "We did not write what we read. Diff: %d\n",
(int) (fpread - written));
}
}
// fread() does not distinguish between EOF and error, we have to check by hand
if (feof(fp)) {
// we have read all, exit
puts("\n\n\tfinish\n");
// No, wait, we want to do it again in a different way, so: no exit
// exit(EXIT_SUCCESS);
} else {
// some error may have occured, check
if (ferror(fp)) {
fprintf(stderr, "Something bad happend while reading \"%s\"\n", filename);
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
}
exit(EXIT_FAILURE);
}
}
// the other way is to read it byte by byte
// reset the filepointers/errors et al.
rewind(fp);
// rewind() should have reseted errno, but better be safe than sorry
errno = 0;
printf("\n\n\tread and print \"%s\" again\n\n\n\n", filename);
// read one byte and print it until end of file
while ((c = fgetc(fp)) != EOF) {
// just print. Gathering them into "source" is left as an exercise
fputc(c, stdout);
}
// clean up
errno = 0;
ret_fclose = fclose(fp);
// even fclose() might fail
if (ret_fclose == EOF) {
fprintf(stderr, "Something bad happend while closing \"%s\"\n", filename);
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
}
exit(EXIT_FAILURE);
}
// The macros EXIT_FAILURE and EXIT_SUCCESS are set to the correct values for
// the OS to tell it if we had an eror or not.
// Using exit() is noot necessary here but there exits teh function atexit()
// that runs a given function (e.g: clean up, safe content etc.) when called
exit(EXIT_SUCCESS);
}
You read from the file twice but only print once.
If the file is to small the first reading will read all of the contents, and the second reading will not produce anything so you don't print anything.
I believe you have to reset the pointer after using fread.
Try fseek(fp, SEEK_SET, 0) to reset the pointer to the beginning of the file. Then print the file.

C assign string from argv[] to char array

I have the following code which reads an file name from the command line and opens this file:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
FILE *datei;
char filename[255];
//filename = argv[1];
//datei=fopen(filename, "r");
datei=fopen(argv[1], "r");
if(datei != NULL)
printf("File opened");
else{
printf("Fehler beim öffnen von %s\n", filename);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
This example works, but I want to write the string from the command line to the char array and pass that char array to to fopen(), but i get the compiler error
Error: assignment to expression with array type filename = argv[1];
What does this error mean and what can I do to fix it?
You must copy the string into the char array, this cannot be done with a simple assignment.
The simplistic answer is strcpy(filename, argv[1]);.
There is a big problem with this method: the command line parameter might be longer than the filename array, leading to a buffer overflow.
The correct answer therefore:
if (argc < 2) {
printf("missing filename\n");
exit(1);
}
if (strlen(argv[1]) >= sizeof(filename)) {
printf("filename too long: %s\n", argv[1]);
exit(1);
}
strcpy(filename, argv[1]);
...
You might want to output the error messages to stderr.
As a side note, you probably want to choose English or German, but not use both at the same time ;-)
An even simpler solution is to just keep a copy of the pointer argv[1] in a char *filename. Unless you modify it yourself, a very bad idea, its contents will not change for the duration of the program execution.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *datei;
char *filename;
if (argc < 2) {
fprintf(stderr, "Fehlendes Dateiname-Befehlszeilenargument\n");
return EXIT_FAILURE;
}
filename = argv[1];
datei = fopen(filename, "r");
if (datei != NULL) {
printf("Datei erfolgreich geöffnet\n");
} else {
fprintf(stderr, "Fehler beim öffnen von %s: %s\n",
filename, strerror(errno));
return EXIT_FAILURE;
}
// ...
fclose(datei);
return EXIT_SUCCESS;
}

Resources