Reading first line by getchar() in c - c

I want to read first line by getchar() but compiler tell me that array A is int type. How can I save my first line char by char in array using getchar?
#include <stdio.h>
int main(void) {
FILE *fp;
int i=0;
char A[200];
int c;
fp = fopen("input.txt", "r");
while ((c=getchar()) != '\n') && i<200) {
A[i]=(char)c;
i++;
}
for(i=0; i<200; i++) {
printf("%s", A[i]);
}
}

Your reading is (almost) fine, the biggest issue is printing.
Before fixing it, though, you should change the call of getchar to fgetc(fp) - something you probably meant to do, because you used fopen.
If you would like to print your line character-by-character, you need to use %c instead of %s format specified, ans stop iterating when you reach the length of the string that you have read. The %s specifier is also fine, as long as you null-terminate your string. It lets you avoid the loop, too:
A[i] = '\0';
printf("%s\n", A);
With printing out of the way, here are a few other things that you need to fix:
Allocate an extra char for null terminator:
char A[201];
You could also stop reading upon reaching character 199 in your loop.
Make sure that the program stops reading when you reach EOF:
while ((c=fgetc(fp)) != '\n') && c != EOF && i<200) {
...
}

As dasblinkenlight said, the %s specifier is used for strings while the %c is used for char. Therefore, your print statement should be
printf("%c\n",A[I]);
To ensure that the file has not ended, you could also use
!feof(fp)
in your while loop. If the file you were reading from contained less than 200 characters, you would run into problems. The feof function checks for the end of the file to ensure you wont read data after the file is ended.

you can give it a try with something like this
#include <stdio.h>
int main(void)
{
FILE *fp;
int i=0;
char A[200];
int c;
fp = fopen("input.txt", "r");
while ((c=getchar()) != '\n' && i<200 )
{
A[i]=(char)c;
i++;
};
for(int j=0; j<i; j++) // print only those item available in array
{
printf("%c", A[j]);
}
}

Related

How can I do a C program that capitalizes the first characters of the words in the file?

#include <stdio.h>
int main()
{
FILE *fp;
int i;
int pos;
fp=fopen("test.txt","r+");
fseek(fp,0,SEEK_END);
pos=ftell(fp);
char ch[pos-1];
fseek(fp,0,SEEK_SET);
ch[0]=ch[0]-32;
i=0;
while(ch[i]=fgetc(fp)!=EOF){
if(ch[i]!=' '){
fseek(fp,1,SEEK_CUR);
i++;
}
else{
fseek(fp,1,SEEK_CUR);
i++;
ch[i]=fgetc(fp);
ch[i]=ch[i]-32;
fprintf(fp,"%c",ch[i]);
}
}
fclose(fp);
}
I want to make C program that capitalizes the first characters of the words in the file. But when I run this code .txt file get wrong.
Is usage of fgetc() wrong?
where is my fault for this question ? And is fscanf moving cursor ?
In the condition for your while loop, you have
ch[i] = fgetc(fp) != EOF
Since != has a high precedence than =, this is equivalent to
ch[i] = (fgetc(fp) != EOF)
Which doesn't evaluate to the character, but rather the 0 or non-zero value from the comparison.
In my opinion, a better way to do this would be to read in the entire string, modify it, then open the file again in writing mode and write back, if you're going to allocate an array for the contents anyways.

How to copy every n-th characters from one char array to another?

I have a program that reads file A and then copies the contents to file B.
I would like to write to file B every third character. I created a loop that rewrites every third item to a new char array. In file B I get strange characters. What am I doing wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
int i;
char full_string[100];
char reduce_string[100];
char file_name_for_read[128];
char file_name_for_save[128];
printf("Enter file name for read...\n");
scanf ("%s", file_name_for_read);
strcat(file_name_for_read,".txt");
FILE *fileA;
fileA=fopen(file_name_for_read,"r");
printf("Enter file name for save...\n");
scanf ("%s", file_name_for_save);
strcat(file_name_for_save,".txt");
FILE *fileB;
fileB=fopen(file_name_for_save,"w");
while(fgets(full_string, sizeof(full_string), fileA) !=NULL)
{
for(i = 2; i < 100; i+=3)
{
reduce_string[i-=2] = full_string[i+=1];
}
fprintf(fileB, "%s", reduce_string);
}
fclose(fileA);
fclose(fileB);
}
What am I doing wrong?
Several things. At minimum,
In your inner loop, you iterate over the full length of full_string, regardless of how many of those bytes were actually read from the file by the most recent fgets().
In your inner loop, you invoke undefined behavior because the expression reduce_string[i-=2] = full_string[i+=1] has two side effects on the value of i that are unsequenced relative to each other.
In that expression, i - 2 is anyway not the index you want except when i is 2, because you increment i by 3 at each iteration. You'll end up filling some positions and skipping others.
You do not add a null terminator at the end of the data copied into reduce_string.
Your strategy does not anyway result in copying every third character of the file; rather, it copies every third character of each line. These differ unless all the line lengths of the input files are multiples of 3.
reads file A and then copies the contents to file B. I would like to write to file B every third character.
If lines are not important,
seems simple to read 3 characters and write the 3rd one.
for(;;) {
fgetc(fileA);
fgetc(fileA);
int ch = fgetc(fileA);
if (ch == EOF) break;
fputc(ch, fileB);
}
or
int ch;
do {
fgetc(fileA);
fgetc(fileA);
ch = fgetc(fileA);
} while (ch != EOF && fputc(ch, fileB) != EOF);
The easiest way is to use a different index for each array, that way each can go at their own speed.
int i,x;
for(i = 0, x=0; i < 1000; i+=3, x++)
{
reduce_string[x] = full_string[i];
}
fprintf(fileB, "%s", reduce_string);
Check this code out. In your code, you have reduce_string[i-=2] = full_string[i+=1]; — I don't know where you come up with it, but this was not working.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
int i;
char full_string[100];
char reduce_string[100];
char file_name_for_read[128];
char file_name_for_save[128];
printf("Enter file name for read...\n");
scanf ("%s", file_name_for_read);
strcat(file_name_for_read,".txt");
FILE *fileA;
fileA=fopen(file_name_for_read,"r");
printf("Enter file name for save...\n");
scanf ("%s", file_name_for_save);
strcat(file_name_for_save,".txt");
FILE *fileB;
fileB=fopen(file_name_for_save,"w");
while(fgets(full_string, 50, fileA) !=NULL)
{
int cnt = 0;
for(i = 2; i < strlen(full_string)-3; i+=3)
{
reduce_string[cnt++] = full_string[i];
}
fprintf(fileB, "%s", reduce_string);
}
fclose(fileA);
fclose(fileB);
}

C - Can't get the number of lines in text file? Are there other ways to get?

I want program count lines in text file by function. It used to work ,but it always return 0 now.
What am I doing wrong?
#include <stdio.h>
int couLineF(FILE* fp){ //count lines in file
int count = 0,ch;
while((ch = fgetc(fp)) != EOF){
if(ch == (int)"\n" ) count++;
}
rewind(fp);
return count;
}
int main(){
FILE *fp = fopen("book.txt","r");
int lines;
if(fp){
lines = couLineF(fp);
printf("number of lines is : %d",lines);
}
return 0;
}
Another question
Are there any other ways to get number of lines in text file?
Your problem is here:
if(ch == (int)"\n" )
You are casting the address of "\n", a string literal, into an int and comparing it with ch. This doesn't make any sense.
Replace it with
if(ch == '\n' )
to fix it. This checks if ch is a newline character.(Use single quotes(') for denoting a character and double quotes(") for a string)
Other problems are:
Not closing the file using fclose if fopen was successful.
Your program won't count the last line if it doesn't end with \n.
There is absolutely no reason to use rewind(fp) as you never use the FILE pointer again.

Read characters from a file and store them in a variable in C

I am trying to read character by character from a file and store the characters in a variable.
Only the content from the first line of the file is required so I am using \n or EOF to stop reading. It is required to store SPACE also.
Here is my program:
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch;
char txt[30];
int len;
fp=fopen("~/hello.txt","r");
ch=fgetc(fp);
while(ch != EOF || ch!="\n")
{
txt[len]=ch;
len++;
ch=fgetc(fp);
}
puts(txt);
}
But I am getting a warning while compiling like comparison between pointer and integer. And when I run it I am getting a segmentation fault.
You're comparing to the wrong thing. Try:
ch != '\n'
^ ^
Also, as spotted in other answers, you're using len without initializing it.
Finally, you do realize fgets can do that as well. You could rewrite the thing to:
if (fgets(txt, sizeof txt, fp))
...
1) len is not initiated
int len=0;
2) From fgetc() page:
int fgetc ( FILE * stream );
so the fgetc() return int and not char so you have to define ch as int
int ch;
3) In addition of the cnicutar remark, the while condition should be checked with the && and not with ||:
while(ch != EOF && ch!='\n')
4) You have to add null terminator charachter at the end of your txt buffer after finishing reading from file.
Add this line after the while loop
txt[len]='\0';
BTW you can read the first line with fscanf() it's more easier. Just use the following code
fscanf(fp, "%29[^\n]", txt);
The "%[^\n]" means that fscanf will read all characters from fp except the '\n' charachter and it will stop reading if it gets this charachter. So the fscanf will read all characters from fp till it find '\n' character and save them into the buffer txt with null terminator charchter at the end.
The "%29[^\n]" means that fscanf will read all characters from fp till it find '\n' character or till it reach 29 readed charchters and save them into the buffer txt with null terminator charchter at the end.
len is not initialised so you're probably attempting to write way beyond the end of txt. The fix is simple - initialise it to 0 on declaration
int len = 0;
In addition to the error pointed out by cnicutar, you should also check the return value from fopen before using fp.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch;
char txt[30];
int len = 0;
fp=fopen("~/hello.txt","r");
if(!fp) {
printf("Cannot open file!\n");
return;
}
ch=fgetc(fp);
while(ch != EOF && ch!= '\n' && len < 30)
{
txt[len] = ch;
len++;
ch=fgetc(fp);
}
txt[len] = 0;
puts(txt);
}
This program may help you to solve your problem.
#include<stdio.h>
int main()
{
FILE *fp;
int ch;
char txt[300];
int len=0;
fp=fopen("tenlines.txt","r");
do{
ch=fgetc(fp);
txt[len]=ch;
len++;
} while(ch!=EOF && ch!='\n');
fclose(fp);
puts(txt);
return 0;
}

What is the easiest way to count the newlines in an ASCII file?

Which is the fastest way to get the lines of an ASCII file?
Normally you read files in C using fgets. You can also use scanf("%[^\n]"), but quite a few people reading the code are likely to find that confusing and foreign.
Edit: on the other hand, if you really do just want to count lines, a slightly modified version of the scanf approach can work quite nicely:
while (EOF != (scanf("%*[^\n]"), scanf("%*c")))
++lines;
The advantage of this is that with the '*' in each conversion, scanf reads and matches the input, but does nothing with the result. That means we don't have to waste memory on a large buffer to hold the content of a line that we don't care about (and still take a chance of getting a line that's even larger than that, so our count ends up wrong unless we got to even more work to figure out whether the input we read ended with a newline).
Unfortunately, we do have to break up the scanf into two pieces like this. scanf stops scanning when a conversion fails, and if the input contains a blank line (two consecutive newlines) we expect the first conversion to fail. Even if that fails, however, we want the second conversion to happen, to read the next newline and move on to the next line. Therefore, we attempt the first conversion to "eat" the content of the line, and then do the %c conversion to read the newline (the part we really care about). We continue doing both until the second call to scanf returns EOF (which will normally be at the end of the file, though it can also happen in case of something like a read error).
Edit2: Of course, there is another possibility that's (at least arguably) simpler and easier to understand:
int ch;
while (EOF != (ch=getchar()))
if (ch=='\n')
++lines;
The only part of this that some people find counterintuitive is that ch must be defined as an int, not a char for the code to work correctly.
Here's a solution based on fgetc() which will work for lines of any length and doesn't require you to allocate a buffer.
#include <stdio.h>
int main()
{
FILE *fp = stdin; /* or use fopen to open a file */
int c; /* Nb. int (not char) for the EOF */
unsigned long newline_count = 0;
/* count the newline characters */
while ( (c=fgetc(fp)) != EOF ) {
if ( c == '\n' )
newline_count++;
}
printf("%lu newline characters\n", newline_count);
return 0;
}
Maybe I'm missing something, but why not simply:
#include <stdio.h>
int main(void) {
int n = 0;
int c;
while ((c = getchar()) != EOF) {
if (c == '\n')
++n;
}
printf("%d\n", n);
}
if you want to count partial lines (i.e. [^\n]EOF):
#include <stdio.h>
int main(void) {
int n = 0;
int pc = EOF;
int c;
while ((c = getchar()) != EOF) {
if (c == '\n')
++n;
pc = c;
}
if (pc != EOF && pc != '\n')
++n;
printf("%d\n", n);
}
Common, why You compare all characters? It is very slow. In 10MB file it is ~3s.
Under solution is faster.
unsigned long count_lines_of_file(char *file_patch) {
FILE *fp = fopen(file_patch, "r");
unsigned long line_count = 0;
if(fp == NULL){
return 0;
}
while ( fgetline(fp) )
line_count++;
fclose(fp);
return line_count;
}
What about this?
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 4096
int main(int argc, char** argv)
{
int count;
int bytes;
FILE* f;
char buffer[BUFFER_SIZE + 1];
char* ptr;
if (argc != 2 || !(f = fopen(argv[1], "r")))
{
return -1;
}
count = 0;
while(!feof(f))
{
bytes = fread(buffer, sizeof(char), BUFFER_SIZE, f);
if (bytes <= 0)
{
return -1;
}
buffer[bytes] = '\0';
for (ptr = buffer; ptr; ptr = strchr(ptr, '\n'))
{
++count;
++ptr;
}
}
fclose(f);
printf("%d\n", count - 1);
return 0;
}

Resources