{"id":6835,"date":"2022-09-05T10:40:21","date_gmt":"2022-09-05T05:10:21","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/"},"modified":"2022-09-05T10:40:21","modified_gmt":"2022-09-05T05:10:21","slug":"solved-segmentation-fault-while-reading-data-from-file","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/","title":{"rendered":"[Solved] Segmentation fault while reading data from file"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-67187725\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"67187725\" data-parentid=\"67187282\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>While you have a good answer addressing your problems with <code>strtok()<\/code>, you may be over-complicating your code by using <code>strtok()<\/code> to begin with. When reading a delimited file with a fixed delimiter, reading a line-at-a-time into a sufficiently sized buffer and then separating the buffer into the needed values with <code>sscanf()<\/code> can provide a succinct (and in the case of your use of <code>atoi()<\/code> a more robust) solution.<\/p>\n<p>Your fields are easily separated in this case using a carefully crafted <em>format-string<\/em>. For example, reading each line into a buffer (<code>buf<\/code> in this case) you can separate each of the lines into the needed values with:<\/p>\n<pre><code>        if (sscanf (buf, \"%d;%c;%15[^;];%c;%d;%c\",      \/* convert to person\/VALIDATE *\/\n                    &amp;person[n].id, &amp;person[n].key, person[n].name,\n                    &amp;person[n].rel, &amp;person[n].age, &amp;person[n].status) == 6)\n<\/code><\/pre>\n<p>The conversion to <code>int<\/code> by <code>sscanf()<\/code> at least minimally validates the integer conversion. Not so with <code>atoi()<\/code> which will happily take <code>atoi (\"my cow\")<\/code> and fail silently returning zero without any indication things have gone wrong.<\/p>\n<p>Note, in every conversion to string, you must provide a <em>field-width<\/em> modifier to limit the number of characters stored to one less than your array can hold (saving room for the <code>'\\0'<\/code> nul-terminating character). Otherwise the use of the <code>scanf()<\/code> family <code>\"%s\"<\/code> or <code>\"%[..]\"<\/code> is no safer than using <code>gets()<\/code>. See Why gets() is so dangerous it should never be used!<\/p>\n<p>The same protection of your array bounds for <code>person[]<\/code> applies on your read loop. Simply keeping a count of the successful conversions and testing before the next read is all you need, e.g.<\/p>\n<pre><code>#define NPERSONS  12        \/* if you need a constant, #define one (or more) *\/\n#define MAXNAME   16\n#define MAXC    1024\n...\n    char buf[MAXC];                                     \/* buffer to hold each line *\/\n    size_t n = 0;                                       \/* person counter\/index *\/\n    Person person[NPERSONS] = {{ .id = 0 }};            \/* initialize all elements *\/\n    \/* use filename provided as 1st argument (stdin by default) *\/\n    FILE *fp = argc &gt; 1 ? fopen (argv[1], \"r\") : stdin;\n    ...\n    while (n &lt; NPERSONS &amp;&amp; fgets (buf, MAXC, fp)) {     \/* protect array, read line   *\/\n        if (sscanf (buf, \"%d;%c;%15[^;];%c;%d;%c\",      \/* convert to person\/VALIDATE *\/\n                    &amp;person[n].id, &amp;person[n].key, person[n].name,\n                    &amp;person[n].rel, &amp;person[n].age, &amp;person[n].status) == 6)\n            n++;        \/* increment count on good conversion *\/\n    }\n<\/code><\/pre>\n<p>As shown with the <code>#define<\/code>s above, don&#8217;t use <em>MagicNumbers<\/em> in your code. (e.g. <code>12<\/code>, <code>16<\/code>). Instead declare a constant at the top of your code that provides a convenient single-location to change if your limits later need adjustment.<\/p>\n<p>In the same vein, do not hardcode filenames. There is no reason you should have to re-compile your code just to read from a different file. Pass the filename as the first argument to your program (that&#8217;s what <code>argc<\/code> and <code>argv<\/code> are for), or prompt the user and take the filename as input. Above, the code takes the filename as the first argument, or reads from <code>stdin<\/code> by default if no argument is provided (like most Unix utilities do).<\/p>\n<p>Putting that altogether, you could do something similar to:<\/p>\n<pre><code>#include &lt;stdio.h&gt;\n\n#define NPERSONS  12        \/* if you need a constant, #define one (or more) *\/\n#define MAXNAME   16\n#define MAXC    1024\n\ntypedef struct Person {\n    int id;\n    char key;\n    char name[MAXNAME];\n    char rel;\n    int age;\n    char status;\n} Person;\n\nint main (int argc, char **argv) {\n\n    char buf[MAXC];                                     \/* buffer to hold each line *\/\n    size_t n = 0;                                       \/* person counter\/index *\/\n    Person person[NPERSONS] = {{ .id = 0 }};            \/* initialize all elements *\/\n    \/* use filename provided as 1st argument (stdin by default) *\/\n    FILE *fp = argc &gt; 1 ? fopen (argv[1], \"r\") : stdin;\n\n    if (!fp) {  \/* validate file open for reading *\/\n        perror (\"file open failed\");\n        return 1;\n    }\n    \n    while (n &lt; NPERSONS &amp;&amp; fgets (buf, MAXC, fp)) {     \/* protect array, read line   *\/\n        if (sscanf (buf, \"%d;%c;%15[^;];%c;%d;%c\",      \/* convert to person\/VALIDATE *\/\n                    &amp;person[n].id, &amp;person[n].key, person[n].name,\n                    &amp;person[n].rel, &amp;person[n].age, &amp;person[n].status) == 6)\n            n++;        \/* increment count on good conversion *\/\n    }\n    if (fp != stdin)   \/* close file if not stdin *\/\n        fclose (fp);\n    \n    for (size_t i = 0; i &lt; n; i++)                      \/* output results *\/\n        printf (\"person[%zu]  %3d  %c  %-15s  %c  %3d  %c\\n\", i,\n                person[i].id, person[i].key, person[i].name,\n                person[i].rel, person[i].age, person[i].status);\n}\n<\/code><\/pre>\n<p>(<strong>note:<\/strong> you only need one call to <code>printf()<\/code> to output any contiguous block of output with conversions. If you have no conversions required, use <code>puts()<\/code> or <code>fputs()<\/code> if end-of-line control is needed)<\/p>\n<p>Lastly, <em><strong>do not skimp on buffer size<\/strong><\/em>. <code>16<\/code> seems horribly short for a <code>name<\/code> field (<code>64<\/code> is still pushing it). By using the <em>field-width<\/em> modifier you are protected against <em>Undefined Behavior<\/em> due to overwriting your array bounds (the code will simply skip the line), but you should add an <code>else { ... }<\/code> condition to output an error in that case. <code>16<\/code> is sufficient for your example data, but for general use, you would want to adjust that to a larger value.<\/p>\n<p><strong>Example Use\/Output<\/strong><\/p>\n<p>With your sample input in the file named <code>dat\/person_id-status.txt<\/code>, you could do:<\/p>\n<pre class=\"lang-none prettyprint-override\"><code>$ .\/bin\/person_id-status dat\/person_id-status.txt\nperson[0]    1  A  John Mott        D   30  Z\nperson[1]    2  B  Judy Moor        S   60  X\nperson[2]    3  A  Kae Blanchett    S   42  y\nperson[3]    4  B  Jair Tade        S   21  W\n<\/code><\/pre>\n<p>Those there the main points that struct me looking over your code. (I&#8217;m sure I&#8217;ve forgotten to mention one or two more) Look things over and let me know if you have further questions.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Segmentation fault while reading data from file <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] While you have a good answer addressing your problems with strtok(), you may be over-complicating your code by using strtok() to begin with. When reading a delimited file with a fixed delimiter, reading a line-at-a-time into a sufficiently sized buffer and then separating the buffer into the needed values with sscanf() can provide a &#8230; <a title=\"[Solved] Segmentation fault while reading data from file\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/\" aria-label=\"More on [Solved] Segmentation fault while reading data from file\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,1912],"class_list":["post-6835","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-import-from-csv"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] Segmentation fault while reading data from file - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Segmentation fault while reading data from file - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] While you have a good answer addressing your problems with strtok(), you may be over-complicating your code by using strtok() to begin with. When reading a delimited file with a fixed delimiter, reading a line-at-a-time into a sufficiently sized buffer and then separating the buffer into the needed values with sscanf() can provide a ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-05T05:10:21+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Segmentation fault while reading data from file\",\"datePublished\":\"2022-09-05T05:10:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/\"},\"wordCount\":514,\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"keywords\":[\"c++\",\"import-from-csv\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/\",\"name\":\"[Solved] Segmentation fault while reading data from file - JassWeb\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\"},\"datePublished\":\"2022-09-05T05:10:21+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-segmentation-fault-while-reading-data-from-file\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Segmentation fault while reading data from file\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\\\/\\\/jassweb.com\"],\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/author\\\/jaspritsinghghumangmail-com\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Segmentation fault while reading data from file - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Segmentation fault while reading data from file - JassWeb","og_description":"[ad_1] While you have a good answer addressing your problems with strtok(), you may be over-complicating your code by using strtok() to begin with. When reading a delimited file with a fixed delimiter, reading a line-at-a-time into a sufficiently sized buffer and then separating the buffer into the needed values with sscanf() can provide a ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/","og_site_name":"JassWeb","article_published_time":"2022-09-05T05:10:21+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Segmentation fault while reading data from file","datePublished":"2022-09-05T05:10:21+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/"},"wordCount":514,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","import-from-csv"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/","url":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/","name":"[Solved] Segmentation fault while reading data from file - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-05T05:10:21+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-segmentation-fault-while-reading-data-from-file\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Segmentation fault while reading data from file"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/6835","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=6835"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/6835\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=6835"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=6835"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=6835"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}