How to create a file for use in c? - c

I have a program:
#include <stdio.h>
#include <string.h>
// ne menuvaj ovde
void wtf() {
FILE *f = fopen("text.txt", "w");
char c;
while((c = getchar()) != EOF) {
fputc(c, f);
}
fclose(f);
}
int main() {
wtf();
FILE *vlezna;
vlezna=fopen("text.txt","r");
float words=0,lines=0,average=0;
int counter=0;
char ch;
while((ch=fgetc(vlezna))!=EOF)
{
if(ch==' ')
words++;
if(ch=='\n');
{
words++;lines++;
}
}
average=words/lines;
printf("%f",average);
fclose(vlezna);
vlezna=fopen("text.txt","r");
while((ch=fgetc(vlezna))!=EOF)
{ words=0;
if(ch==' ')
words++;
if(ch=='\n')
{
words++;
if(words<average) counter++;
}
}
fclose(vlezna);
printf("%d",counter);
}
So i presume the first function writes to the file. But i guess the file should be created first, and i don't know how(except with right click new text document).
Also i didn't know how to return the pointer at the beginning of the file so i closed it and opened it again presuming that that will return the pointer at the beginning?

fopen create the file if it does not exist if option is "w".
Read the documentation here : http://www.cplusplus.com/reference/cstdio/fopen/

There is no need to create. For the man page of fopen:
``w'' Truncate to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
To set the file pointer use fseek. However, to read and write you need different open flags.

Related

How to take first row from this list of text?

I have a list of columns containing text but I just to fetch first upper row from this list. How to do that?
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
Your stop condition is EOF, everything will be read to the end of the file, what you need is to read till newline character is found, furthermore EOF (-1) should be compared with int type.
You'll need something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fr;
int c;
if(!(fr = fopen("prog.txt", "r"))){ //check file opening
perror("File error");
return EXIT_FAILURE;
}
while ((c = fgetc(fr)) != EOF && c != '\n')
{
printf("%c",c); /* display on screen*/
}
fclose(fr);
return EXIT_SUCCESS;
}
This is respecting your code reading the line char by char, you also have the library functions that allow you to read whole line, like fgets() for a portable piece of code, or getline() if you are not on Windows, alternatively download a portable version, and, of course you can make your own like this one or this one.
For whatever it's worth, here's an example that uses getline
#include <stdio.h>
int main()
{
FILE *fr;
char *line = NULL;
size_t len = 0;
ssize_t nread;
if (!(fr = fopen("prog.txt", "r"))) {
perror("Unable to open file");
return 1;
}
nread = getline(&line, &len, fr);
printf("line: %s, nread: %ld\n", line, nread);
fclose(fr);
return 0;
}
Some notes:
getline() can automatically allocate your read buffer, if you wish.
getline() returns the end of line delimiter. You can always strip it off, if you don't want it.
It's ALWAYS a good idea to check the status of I/O calls like "fopen()".
just replace EOF as '\n'(new line char). Than your code will read until reaching the new line. Here is what it looks like:
#include <stdio.h>
int main()
{
FILE *fr;
char c = ' ';
fr = fopen("prog.txt", "r");
while(c != EOF && c != '\n')
{
c = fgetc(fr); /* read from file*/
if(c != EOF){
printf("%c",c); /* display on screen*/
}
}
fclose(fr);
return 0;
}
I have not tested it yet but probably work. Please let me know if there is some problem with the code i will edit it.
Edit1:char c; in line 5 is initialized as ' ' for dealing with UB.
Edit2:adding condition (c != EOF) to while loop in line 7, for not giving reason to infinite loop.
Edit3:adding if statement to line 10 for not printing EOF which can be reason for odd results.

Reading and writing into a file in c

I need to write into a file with uppercase some strings ,then to display on screen with lowercase. After that ,I need to write into file the new text (lowercase one). I write some code ,but it doesn't work. When I run it , my file seems to be intact and the convert to lowercase don't work
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void main(void) {
int i;
char date;
char text[100];
FILE *file;
FILE *file1;
file = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","r");
file1 = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","w");
printf("\nSe citeste fisierul si se copiaza textul:\n ");
if(file) {
while ((date = getc(file)) != EOF) {
putchar(tolower(date));
for (i=0;i<27;i++) {
strcpy(text[i],date);
}
}
}
if (file1) {
for (i=0;i<27;i++)
fprintf(file1,"%c",text[i]);
}
}
There are several problems with your program.
First, getc() returns int, not char. This is necessary so that it can hold EOF, as this is not a valid char value. So you need to declare date as int.
When you fix this, you'll notice that the program ends immediately, because of the second problem. This is because you're using the same file for input and output. When you open the file in write mode, that empties the file, so there's nothing to read. You should wait until after you finish reading the file before you open it for output.
The third problem is this line:
strcpy(text[i],date);
The arguments to strcpy() must be strings, i.e. pointers to null-terminated arrays of char, but text[i] and date are char (single characters). Make sure you have compiler warnings enabled -- that line should have warned you about the incorrect argument types. To copy single characters, just use ordinary assignment:
text[i] = date;
But I'm not really sure what you intend with that loop that copies date into every text[i]. I suspect you want to copy each character you read into the next element of text, not into all of them.
Finally, when you were saving into text, you didn't save the lowercase version.
Here's a corrected program. I've also added a null terminator to text, and changed the second loop to check for that, instead of hard-coding the length 27.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void main(void) {
int i = 0;
int date;
char text[100];
FILE *file;
FILE *file1;
file = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","r");
printf("\nSe citeste fisierul si se copiaza textul:\n ");
if(file) {
while ((date = getc(file)) != EOF) {
putchar(tolower(date));
text[i++] = tolower(date);
}
text[i] = '\0';
fclose(file);
} else {
printf("Can't open input file\n");
exit(1);
}
file1 = fopen("C:\\Users\\amzar\\Desktop\\PC\\Pregatire PC\\Pregatire PC\\file\\da.txt","w");
if (file1) {
for (i=0;text[i] != '\0';i++)
fprintf(file1,"%c",text[i]);
fclose(file1);
} else {
printf("Can't open output file\n");
exit(1);
}
}

Extra character at end while copying?

This is making me nuts I am trying to make a simple program to copy any type of file using the following code but the result I get is unexpected (one or two extra characters at the end of copied file?). For instance if my original file has This is an example the copied file contains This is an exampleÿ
CODE
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp,*fpp;
char pbuff, fname[32];
int i;
printf(" FILE NAME TO OPEN : ");
scanf(" %32s", fname);
fp = fopen(fname, "rb");
fpp = fopen("file", "wb");
if(fp==NULL)
{
printf("NO SUCH FILE. EXITING NOW.");
getch();
exit(1);
}
while(!feof(fp))
{
pbuff = fgetc(fp);
fputc(pbuff, fpp);
}
printf("SUCCESSFULLY CREATED!");
fclose(fp);
fclose(fpp);
getch();
return(0);
}
Can anyone help me out with this one? I will be really very thankful.
The reason is that feof (like most end-of-file indicators in most languages/environments) is only set AFTER the end-of-file has been reached. Since you write the character and only then check the EOF status, you're writing 1 too many characters. fgetc's return value is a predefined EOF if the end-of-file was reached during the call.
You could solve that in 1 of 2 ways:
while(true)
{
pbuff = fgetc(fp);
if(feof(fp))
break;
fputc(pbuff, fpp);
}
Or: (edit as melpomene correctly noticed!)
// Change pbuff to type int in the declartion, and then...
while(true)
{
pbuff = fgetc(fp);
if(EOF == pbuff)
break;
fputc(pbuff, fpp);
}

How to write using space and more than one line in C?

I want to write a text and save it in .txt using <stdio.h> and <stdlib.h>. But with this way, I only could save one line, no more.
int main()
{
file*pf;
char kar;
if ((pf = fopen("try.txt","w")) == NULL)
{
printf("File couldn't created!\r\n");
exit(1);
}
while((kar=getchar()) != '\n')
fputc(kar, pf);
fclose(pf);
}
Instead of
char kar;
...
while((kar=getchar()) != '\n')
fputc(kar, pf);
use
int kar;
// Use int for type of kar
...
while((kar=getchar()) != EOF )
// ^^^
fputc(kar, pf);
'\n' means end of line. Here, you are looking for end of file. So, use macro EOF instead of '\n' in your code.
Full Working Code which puts multiple line into your text file. To end the input from terminal just press Ctrl + Z
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *pf;
char kar;
if ((pf = fopen("try.txt","w")) == NULL)
{
printf("File couldn't created!\r\n");
exit(1);
}
while((kar=getchar()) != EOF)
fputc(kar, pf);
fclose(pf);
return 0;
}

Struct sscanf not working as it should?

i am trying to sipmply input some data into a struct from a file.
I have used the same excact code in a different program and it works as it should?
I dont know where i am wrong.
Shouldnt the code below work ? Maybe i am not that familiar with sscanf .I would like some help. Thank you.
The txt file is like this:
foo.var 1241
poa.org 421
aeraf.gr 5456
oiggdf.po 98843
Code:
struct filedata
{
char fname[50];
int fsize;
};
int main()
{
char line[60];
int i=0;
int numberoffiles=0;
int lines=0;
int ch=0;
FILE *fp = fopen("mytext.txt","r");
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
struct filedata file[lines];
numberoffiles=lines + 1;
if(fp == (FILE*)NULL)
{
fprintf(stderr,"Cannot Open File\n");
exit (-1);
}
else
{
while (fgets(line,60,fp)!=NULL)
{
sscanf(line,"%s %d",file[i].fname,&file[i].fsize);
i++;
}
}
}
Your loop that counts the number of lines reads the entire file so that the current position is at the end of the file when you begin your second loop. Consider using rewind() before your second loop to move back to the start of the file.
Also, your test to see if fp is NULL should go right after the open() call. Otherwise, your code that reads the number of lines will fail.

Resources