Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am confused that how to give break line after every word which is present in a file.
Words in text file
Name Date of birth <---- I put this in code
John 02\02\1999 <---- I want to jump to this line
I want this
Here is your: Name
Here is your: Date of Birth
But it is giving me this
Here is your: N
Here is your: a
Here is your: m
Here is your: e
And I don't know how to get it.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
char ch;
if(fr != NULL){
while(!feof(fr)){
ch = fgetc(fr);
printf("Here is your %c\n: ", ch);
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
Within your while loop instead of immediately printing the character that you read, store the char in a char array. Add an if statement that does a comparison that checks if the read char is a space character. If it is you should print the stored array and set the index of the array back to 0.
Example:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fr = fopen("file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
//printf("%c\n", ch[index]);
if(ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your: %s\n", ch);
index = 0;
}
else {
index++;
}
}
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
Based on the line of text of the file provided we can assume that if the first letter of the word is in uppercase then it is the start of the next sentence:
Name Date of birth ID card number Phone number Address Account Fixing year
And use this to divide the line into sentences.
So here is the code by Christopher changed to group the words into sentences:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
FILE * fr = fopen("file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
if(index > 0 && ch[index-1] == ' ' && isupper(ch[index])) {
ch[index-1] = '\0';
printf("Here is your: %s\n", ch);
ch[0] = ch[index];
index = 1;
}
else {
index++;
}
}
ch[index] = '\0';
printf("Here is your: %s\n", ch);
fclose(fr);
}
else{
printf("Unable to read file.");
}
return 0;
}
Related
I've been trying to figure out how to print the contents any file from stdin in column 2 and 4 with ',' being the input delimiter (using c).
For example, if the file's contents were:
abcd,55555,string,22222
it would print to stdout:
55555,22222,
I'm not sure why it prints blank
#Astormooke is right about progressing col - since you need to consider the case where valueinarr(col, arr) returns false.
But another issue I foresee is your declaration for col - this should go outside of the for loop, otherwise you'll just be resetting it each time.
Just glancing at your code, it appears that the control flow will never make it to
col++
if
col != 2 or col != 4
With that, we see since it starts as 1 you will never make it to your print statement.
You are nesting in a wrong way, mainly. Also there are some bad practices out there in your code, so I took some freedom to do this:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int valueinarr(int val,int arr[])
{
for(int j=0; j<2; j++)
{
if (val==arr[j])
{
return 1;
}
}
return 0;
}
int main(int argc,char *argv[])
{
int arr[2]={2,4};
char word[101];
FILE *fp;
fp = freopen(0,"r",stdin);
while(fscanf(fp,"%[^\n]\n",word)!=EOF)
{
int col=1;
for(int count=0;count<(strlen(word));count++)
{
if(valueinarr(col,arr))
{
printf("%c",word[(count)]);
}
if(word[count]==',') col++;
}
printf("\n");
}
fclose(fp);
return 0;
}
Although this code will solve your problems with input in some expected format, I must say: this code IS BAD in many ways that are not of part of your question.
If you are going to solve this using a simple approach, you can use strtok() function and a counter to output what you want:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int counter;
char word[101] = "\0";
char *token = NULL;
FILE *fp = fopen("abc.txt", "r");
if(!fp)
{
perror("abc.txt: ");
exit(-1);
}
while(fscanf(fp, " %[^\n]\n", word) != EOF)
{
printf("Contents: %s\n", word);
counter = 1;
token = strtok(word, ",");
while(token != NULL)
{
if(counter == 2 || counter == 4)
printf("Col %d: %s\n", counter, token);
counter++;
token = strtok(NULL, ",");
}
}
fclose(fp);
return 0;
}
OUTPUT:
Contents: 3333,44444,55555,88888,111111
Col 2: 44444
Col 4: 88888
I am trying to give an if statement to check if a particular name is present in text file, then give access to it otherwise give error message.
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("For person details, please enter the person name: \n");
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
int catch, i=0, index=0;
char ch[100];
printf("Enter your Name: ");
if (scanf("%s", )){ // Don't know what to put here?
perror("Error while reading!");
return 0;
}
catch = fgetc(fr);
while(catch != EOF){
ch[index] = catch;
if (ch[index] == ' '){
ch[index] = '\0';
printf("Here is your result: %s\n",ch);
index = 0;
i++;
}
else
index++;
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Simply the program firstly opens a file and asks for a user input and verifies if the provided content is case-sensitively matched with the file. If so, then it'll let the program access the entire file and display on the screen, to do that, we must use another FILE b/c the old *fp is already manipulated and in case it's reused, it may display wrong data.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("file.txt", "r"); // for verification
FILE *fp1 = fopen("file.txt", "r"); // for future use
char ch[50], str[50];
short int FLAG = 0;
printf("Enter the string: ");
scanf("%s", &str); // asks for input
while (fscanf(fp, "%s", ch) != EOF) {
if (!strcmp(ch, str)) { // checks if a string matches provided by the user
printf("Found! Here's your details...\n\n");
FLAG = 1;
}
}
if (!FLAG == 1) { // no? exits.
printf("Not found, access denied!\n");
return -1;
}
fclose(fp);
int c = fgetc(fp1); // yes? let's go...
while (c != EOF) {
printf("%c", c); // displays containing data
c = fgetc(fp1);
}
fclose(fp1);
return 0;
}
You'll want to add a variable for your scanf output:
char name[100];
if (scanf("%s", name) != -1)
// ...
Then to compare both you'll use strcmp.
#include <string.h>
//...
if (strcmp(ch, name) == 0)
// both are equal
Note that you can access documentation for scanf and strcmp by typing man scanf or man strcmp in your terminal.
int main()
{
printf("For person details, please enter the person name and id card
number: \n");
printf("Enter your Name: ");
char personName[100];
scanf("%s", personName);
printf("Enter your card number: ");
int cardNumber;
if (scanf("%d", &cardNumber)){
printf("no error detected");
}
else{
printf("error while reading");
}
return 0;
}
The fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
printf("For person details, please enter the person name: \n");
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
int catch, i = 0, index = 0;
char ch[100] = { 0 };
if (fr == NULL)
{
perror("Invalid file opening!");
return 1;
}
printf("Enter your Name: ");
fgets(ch, 100, fr);
size_t len = strcspn(ch, "\n");
ch[(len < 100) ? (len) : (99)] = 0; // For file safety checking
if (strlen(ch)) { // Don't know what to put here?
perror("Error while reading!");
return 1;
}
catch = fgetc(fr);
while (catch != EOF) {
ch[index] = catch;
if (ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your result: %s\n", ch);
index = 0;
memset(ch, 0, 100);
i++;
}
else
{
index++;
}
catch = fgetc(fr);
}
fclose(fr);
return 0;
}
Whenever I make ch[index]==0, it gives me first word from text file but whenever I select ch[index]==1, it gives me nothing. How to make this if statement working?
#include <stdio.h>
#include<stdlib.h>
int main(){
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
if(index[ch]==1){ // here is if statement
if(ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your %s: \n",ch);
index = 0;
}
else { index++; }
}
}
fclose(fr);
}
else{ printf("Unable to read file."); }
return 0;
}
For a start you have an fclose(fr) inside your i loop, but then you never open the file again. You are also incrementing i inside the loop a second time, which is never good in practice.
try this:
for (int i=0; i<8; i++){
fr = fopen("/home/bilal/Documents/file.txt","r");
index = 0;
if(fr != NULL){
and remove the fopen from the top.
There is probably a better way than opening and closing the file on each loop iteration.
Here is a code that should work and show the second word, although I didn't test it:
#include <stdio.h>
//#include <stdlib.h> //not needed
int main(void)
{
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
char ch[100];
int index = 0, c, i = 0;
//for loop is useless
if (fr == NULL)
{
printf("Unable to read file.");
return 0;
//I prefer error checking without a giant if statement, but it's up to you
}
c = fgetc(fr); //fgetc() returns an int, not char
while (c != EOF)
{
ch[index] = c;
if (ch[index] == ' ')
{
if (i == 1)
{
ch[index] = '\0';
printf("Here is your string: %s\n", ch); //The format seemed weird to me, that's why I changed it, use what you need
}
index = 0;
i++;
}
else
index++;
c = fgetc(fr);
}
fclose(fr);
//return 0; //not needed in C99 or later
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working on a project. there is a .txt file that includes negative integers like this
0 -1 0
-1 20 -1
0 -1 0
My problem is I couldn't read negative numbers. What is your suggestions for this problem?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE *fptr;
char letter;
fptr = fopen(argv[1],"r");
if(fptr == NULL){
printf("Please provide an argument\n");
exit(1);
}
while ( ( letter = fgetc(fptr) ) != EOF ) {
printf("%c",letter);
}
printf("\n");
fclose(fptr);
return 0;
}
You can try this to read the lines from the file and then parse your numbers.
getline reads a line from your file and strtok then gives you a string until the specified delimeter (space in your case). Hope this helps.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * fptr = fopen(argv[1],"r");;
char * line = NULL;
size_t lineSize = 0;
if(fptr == NULL){
printf("Please provide an argument\n");
exit(1);
}
while(getline(&line, &lineSize, fptr) != -1) {
line[strcspn(line, "\n")] = 0;
printf("%s\n", line);
char * token = strtok(line, " ");
printf("%s\n", token);
while((token = strtok(NULL, " ")) != NULL) {
printf("%s\n", token);
}
}
fclose(fptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char file_name[50], ch, text[140];
int i;
printf("Enter a file name to create :");
scanf("%s", file_name);
fp = fopen(file_name,"w");
if(fp == NULL)
{
printf("The file %s could not open !", file_name);
exit(EXIT_FAILURE);
}
printf("Enter some text into %s : (enter * to finish)\n", file_name);
while((ch=getchar()) != '*')
{
for(i=0;i<140;i++)
text[i] = ch;
}
for(i=0;i<140;i++)
{
fprintf(fp,"%c",text[i]);
}
fclose(fp);
printf("Your datas has been successfully copied into file %s",file_name);
return 0;
}
It creates the file but does not copies the content of the array to the user created file. So it just creates empty file. In which part I have mistake can anyone help to fix this problem ?
See the below code block, here for loop is unnecessary, outer while loop is enough.
while((ch=getchar()) != '*')
{
for(i=0;i<140;i++) /* 140 times same char you are copying into text */
text[i] = ch;
}
It should be
int i = 0;
while((ch=getchar()) != '*' && (i < 140)) { /* just one more condition so that it should exceeds 140 char */
text[i] = ch;
i++; /* when loop fail i is the count of no of char to be written to file */
}
And while putting data into file using fprintf()
for(index = 0;index < i ;index++) { /* i is the count */
fprintf(fp,"%c",text[index]);
}