Could you help me with the creation of a text file as right now the *fp pointer to the file is returning NULL to the function fopen ?
Using the library errno.h and extern int errno I get "Value of errno: 22".
if (!fp)perror("fopen") gives me "Error opening file: Invalid argument".
In my main function I enter the name of the file:
void main()
{
float **x;
int i,j;
int l,c;
char name_file[30];
FILE *res;
/* some lines omitted */
printf("\nEnter the name of the file =>");
fflush (stdin);
fgets(name_file,30,stdin);
printf("Name of file : %s", name_file);
res=creation(name_file,l,c,x);
printf("\nThe created file\n");
readfile(res,name_file);
}
The function to create the text file:
FILE *creation(char *f_name,int l, int c, float **a) // l rows - c colums - a array
{ FILE *fp;
int i,j;
fp = fopen(f_name,"wt+"); // create for writing and reading
fflush(stdin);
/* The pointer to the file is NULL: */
if (!fp)perror("fopen"); // it's returning Invalid argument
printf("%d\n",fp); //0 ??
if(fp==NULL) { printf("File could not be created!\n"); exit(1); }
fflush(stdin);
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
fprintf(fp,"%3.2f",a[i][j]); // enter every score of the array in the text file
}
fprintf(fp,"\n");
}
return fp;
}
Function to read the file and check if it is correct:
**void readfile(FILE *fp,char *f_name)**
{
float a;
rewind(fp);
if(fp==NULL) { printf("File %s could not open\n",f_name); exit(1); }
while(fscanf(fp,"%3.2f",&a)!= EOF)
printf("\n%3.2f",a);
fclose(fp);
}
There are quite a few wrong things your code.
1.
The correct signatures of main are
int main(void);
int main(int argc, char **argv)
int main(int argc, char *argv[])
See What are the valid signatures for C's main() function?
2.
The behaviour of fflush(stdin) is undefined. See Using fflush(stdin).
fflush works with output buffers, it tells the OS that is should write
the buffered content. stdin is an input buffer, flushing makes no sense.
3.
Use fgets like this:
char name_file[30];
fgets(name_file, sizeof name_file, stdin);
It's more robust using sizeof name_file because this will give you always
the correct size. If you later change the declaration of name_file to
an char array with less than 30 spaces, but forget to change the size parameter in fgets, you
might end up with a buffer overflow.
4.
You are passing to creation the uninitialized pointer p that is pointing
to nowhere. In said function you cannot read nor write with the pointer a.
You need to allocate memory prior to the call of creation. At least judging
from the code you posted.
5.
fgets preserves the newline ('\n') character, so
name_file is containing the newline character. I really don't know if newline
is allowed in file names. I did a google search but found conflicting answers.
I don't think that you want to have newlines in your file names, anyway. It's
best to remove it before passing it to fopen (which might be the reason for
the error 22):
char name_file[30];
fgets(name_file, sizeof name_file, stdin);
int len = strlen(name_file);
if(name_file[len - 1] == '\n')
name_file[len - 1] = 0;
Related
I am writing a basic program to copy text to another text file. But in the console window after entering the filename from where text should be taken, the program ends and does not go further. How can I solve this problem?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1, filename2;
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s", filename1);
infile = fopen("filename1", "r");
printf("Enter a input file name:");
scanf("%s", filename2);
outfile = fopen("filename2", "w");
if (infile == NULL || outfile == NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
char characters;
do {
characters = getc(infile);
fprintf(outfile,"%s", characters);
printf("%s", characters);
} while (!feof(infile));
fclose(infile);
fclose(outfile);
return 0;
}
There are a few problems with your program:
You are using char variables to hold names of files. These variables should be char arrays or pointers to the first char of some allocated memory.
fopen("filename2", "w") seems wrong. Although, the first argument should be a char *, you are not reading / writing the files you just asked the user to enter.
fprintf(outfile,"%s",characters) - You are using %s to print characters. This will invoke UB.
char characters - The last character of a file, the EOF character is guaranteed to fit in an int. The characters variable should be declared as an int so that it can hold the EOF character.
Here is the program that works:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char filename1[10], filename2[10];
FILE *infile;
FILE *outfile;
printf("Enter a data file name:");
scanf("%s",filename1);
infile = fopen(filename1, "r");
printf("Enter a input file name:");
scanf("%s",filename2);
outfile = fopen(filename2, "w");
if (infile==NULL || outfile==NULL) {
printf("Problem in opening files");
exit(0);
}
printf("files opened successfully");
int characters;
/*do {
characters=getc(infile);
fprintf(outfile,"%s",characters);
printf("%s",characters);
} while(!feof(infile));
*/
while ((characters = getc(infile)) != EOF) {
fprintf(outfile, "%c", characters);
printf("%c", characters);
}
fclose(infile);
fclose(outfile);
return 0;
}
There are a number of issues.
char filename1, filename2;
This only allows filename1 and filename2 to hold a single char - not a C string. You need to reserve memory as a char array. Like:
char filename1[64], filename2[64]; // Allow 63 chars for file name
Then
scanf("%s",filename1);
is really bad as it allows the user to overflow your input buffers. Consider using fgets or at least do:
scanf("%63s",filename1); // Limit user input to 63 chars as the buffer is 64
// The "last" char is for the string termination
Then the loop:
First, characters shall be int so that you can check for EOF. Further, check directly on getc instead of using feof. And don't use %s for printing a single char to the output file - use %c. Like
int characters;
while(1) {
characters=getc(infile);
if (characters == EOF) break; // Break (aka jump out of the loop) on
// end-of-file or errors
fprintf(outfile,"%c",characters); // %c instead of %s
// or use: putc(characters, outfile)
// instead of fprintf
printf("%s",characters);
}
I need to scan 3 strings and an integer from an already existing file, and save them each as an element in an array of structures. The file is formatted as such:
string1 string2 integer string3
string1 string2 integer string3
... and so on.
when fscanf-ing for them, it correctly scans string1, the integer, and string3. However, string2 always appears to create an error when scanning it, and when any of the string2's are printed, they are either cut off short, or have some odd ASCII symbol, like a question mark in a box; it also sometimes triggers the system "bell" sound.
I've tested collecting the strings through fscanf for each different one, and it is only the second one that ever messes up.
A stripped-down version of my code, highlighting the issue
struct carinfo
{
char name[10];
char make[15];
int number;
char color[10];
}car[4];
filepointer = fopen("file.txt", "r");
while(!feof(filepointer))
{
for(i=0;i<4;i++)
{
fscanf(filepointer, "%s %s %d %s", &car[i].name[10],
&car[i].make[15], &car[i].number, &car[i].color[10]);
printf("%s\n", &car[i].make[15]);
}
}
my expected result is that the second string will scan properly, and be stored in its entirety to its element in the array of structures; instead, the value is usually cut off (at around 2-3 characters instead of 15) and contain weird ASCII symbols.
Changing fscanf() function to this, will solve your issue.
Code
fscanf(filepointer, "%s %s %d %s", car[i].name,
car[i].make, &car[i].number, car[i].color);
You can find true way of using fscanf() in cplusplus.com:
char str [80];
FILE * pFile;
pFile = fopen ("myfile.txt","w+");
fscanf (pFile, "%s", str);
But as chris-dodd stated at comment section using feof(filepointer) inside while loop not correct.
This code below i correct it by using fscanf() return value.
I obtain this way in a stack overflow answer by lio
Complete version of your program
main.c
#include <stdio.h>
struct carinfo
{
char name[10];
char make[15];
int number;
char color[10];
}car[4];
int main(){
int i=0;
FILE* filepointer = fopen("file.txt", "r");
if(!filepointer){
printf("can't open file\n");
}
int ret=0;
do {
for(i=0;i<4;i++){
ret=fscanf(filepointer, "%s %s %d %s", &car[i].name,
&car[i].make, &car[i].number, &car[i].color);
printf("%s\n", &car[i].make);
}
} while (ret != EOF);
return 0;
}
file.txt
salam beshoma 10 daram
kee innak 15 inomikhonid!
I'm trying to make a program in c90 which will read some words from a txt file and copy them to a matrix array. It seems that the compilation is all right but there is a thread named "EXC_BAD_ACCESS(code=1 adress=0x68). can you help me figure out where the problem is??
int main(int argc, char *argv[]) {
FILE *input;
char words[10][30];
int i,a;
input=fopen("test.txt","rt");
for(i=0;i<10;i++){
a = fscanf(input,"%s", words[i]);
printf("%2d %s\n", a, words[i]);
}
fclose(input);
return 0;
}
Check that your file is actually being opened, otherwise printf() will try to print out random memory which may go beyond the bounds of what you have actually allocated and cause an error.
input = fopen("test.txt", "rt");
if (!input)
{
perror("Failed to open file");
exit(1);
}
You may also want to check that a == 1, i.e. that the fscanf() also succeeds.
I am trying to pass a string into a function in C. That string will entered by the user and then passed on to the function to write to a text file. Iknow this seems very basic but I am just learning C.
#include <stdio.h>
#include <string.h>
void read() {
char text[50][30],buffer[150];
int i=0;
FILE *file_in;
file_in=fopen("test.txt","r");
if (file_in == NULL) {
printf("Error opening file\n");
}
while (fgets(buffer,150,file_in)) {
strcpy(text[i],buffer);
printf("line %d: %s\n",i,text[i]);
i++;
}
getchar();
fclose(file_in);
}
void write(char str[])
{
FILE *file_in;
file_in=fopen("test.txt","a");
if (file_in == NULL) {
printf("Error opening file\n");
}
//write to the file
fprintf(file_in, "\n%s", str);
// fputs(str, file_in);
fclose(file_in);
}
int main()
{
read();
char msg[50];
printf("Enter some text: ");
puts(msg);
write(msg);
return 0;
}
It writes to the file, but it writes weird characters, not what I actually type. What amI doing wrong?
It looks like you've confused gets with puts. puts writes a string to the console. gets reads a string from the console. Switch them out and your program should work.
Microsoft's compiler often warns against insecure or deprecated functions, like gets. You may use fgets instead, as it doesn't allow buffer overflows.
Here's an example:
fgets(msg, 50, stdin);
or
fgets(msg, sizeof(msg), stdin);
First of all: Don't call your functions read() and write() — pick something more specific. The function names read() and write() are already used by the system for low-level file operations, and trying to define them yourself will cause unexpected behavior.
Second: you are never initializing the contents of the msg variable or reading any data into it, so its contents will be random. (Remember that puts() prints data; it doesn't read anything.)
When you write char msg[50];, it contains indeterminate values. It's not zero-initialized or anything.
The puts(msg); line writes this garbage out, and then write(msg); writes that garbage to a file.
I guess you intended to have some code for inputting text, after the printf and before the puts.
NB. In your read() function (which you don't call yet), you should make the fgets buffer size match the width of your array , and you should check you don't run off the end of your array if the file has many lines.
Also it would be wise to name your functions something other than read and write, because in a POSIX environment there are already functions by that name which may clash.
Here is the solution:
#include <stdio.h>
#include <string.h>
int read() {
char text[50][30],buffer[150];
int i=0;
FILE *file_in;
file_in=fopen("test.txt","r");
if (file_in == NULL) {
printf("Error opening file\n");
}
while (fgets(buffer,150,file_in)) {
strcpy(text[i],buffer);
printf("line %d: %s\n",i,text[i]);
i++;
}
// getchar();why you were using this?
fclose(file_in);
// return 0;
}
void write(char str[])
{
FILE *file_in;
file_in=fopen("test.txt","a");
if (file_in == NULL) {
printf("Error opening file\n");
}
//write to the file
fprintf(file_in, "\n%s", str);
// fputs(str, file_in);
fclose(file_in);
}
int main()
{
char msg[50];
read();
printf("Enter some text: ");
// getchar();
gets(msg);//It reads in msg
write(msg);
return 0;
}
I can't seem to work it out. I am using a .c code that opens a file and reads each line. I would like to save in char*substr 4 characters from the line 9 inside the txt file. The line 5 contains
name=Me She; I would like to have in char*substr just Meli.Need help. THX
Here is the c code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
char str[128];
char str1[128];
if((fp = fopen("/home/folder/file.txt", "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
int lin=0;
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
if (lin==8)
{
char *c= (char *) malloc(sizeof(char)*strlen(str)+1);
c= strndup(str, strlen(str)-5);?? not working?!!!
printf("d is:",c);
}
lin=lin+1;
}
fclose(fp);
return 0;
}
Your printf is wrong. change it to printf("d is %s\n",c);.
By the way, strdup allocate the memory needed, so you don't have to allocate it yourself. (In fact, you have a memory leak).
You're calling malloc() and then directly overwriting its result with that of calling strndup(), this leaks memory.
Also, the logic in the strndup() call looks wrong. If you want to skip the first 5 characters, you should have str + 5.
If you have strdup(), use:
if (lin==9)
{
char *name = strdup(str + 5);
printf("name is: '%s'\n", name != NULL ? name : "(failed)");
}
Then you should probably break out of the loop. Also note that the pointer name goes out of scope, so it's not available to code outside the loop for instance.